Hi i am trying to make the Elapsed event of the Timer.Timer class fire on my main thread.
I am restricted to VS 2008, .net 3.5…
In this post:
Do C# Timers elapse on a separate thread?
it is stated that using a SynchronizingObject will make the handler execute on the thread that owns the object.
So I tried this:
class MyTimer
{
private readonly Timer timer;
public MyTimer(ISynchronizeInvoke synchronizingObject)
{
Console.Out.WriteLine(Thread.CurrentThread.ManagedThreadId);
timer = new Timer(1000);
timer.SynchronizingObject = synchronizingObject;
timer.Elapsed +=
delegate
{
timer.Stop();
Thread.Sleep(2000);
Console.Out.WriteLine(Thread.CurrentThread.ManagedThreadId);
timer.Start();
};
timer.Start();
}
}
class Program
{
static void Main(string[] args)
{
ISynchronizeInvoke syncObject = new Control();
var mytimer = new MyTimer(syncObject);
Console.ReadKey();
}
}
But the output is: 1,4,4,4,4…
Why is that? How do i make the Elapsed handler execute on the mainthread.
I tried using SynchronizingObject for an event
but that didn’t help either:
public static ElapsedEventHandler Wrap(ElapsedEventHandler original, ISynchronizeInvoke synchronizingObject)
{
return (sender, args) =>
{
if (synchronizingObject.InvokeRequired)
{
synchronizingObject.Invoke(original, new object[] { sender, args });
}
else
{
original(sender, args);
}
};
}
and:
timer.Elapsed += Wrap(
delegate
{
timer.Stop();
Thread.Sleep(200);
Console.Out.WriteLine(Thread.CurrentThread.ManagedThreadId);
timer.Start();
},
synchronizingObject);
But still no success… everytime InvokeRequired is false…
forcing debug into the invoke causes a invalidoperation: “Invoke or BeginInvoke cannot be called on a control until the window handle has been created.”
last resort would be to look into:
http://www.codeproject.com/Articles/12082/A-DelegateQueue-Class?msg=3655119#xx3655119xx
but is that really necessary? or is there some simpler solution?
I found a solution using DispatcherTimer
and Dispatcher.Run() to start the message pump in a new thread. To stop the dispatcher and exit the service smoothly i used