I am feeling like a total noob asking this, but anyway, here it goes:
I was wondering what the easiest way of synchronizing events from different threads is.
Some sample code:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("# started on:" + Thread.CurrentThread.ManagedThreadId);
tt t = new tt();
t.First += new EventHandler(t_First);
t.Second += new EventHandler(t_Second);
Task task = new Task(new Action(t.Test));
task.Start();
while (true)
{
Console.ReadKey();
Console.WriteLine("# waiting on:" + Thread.CurrentThread.ManagedThreadId);
}
}
static void t_Second(object sender, EventArgs e)
{
Console.WriteLine("- second callback on:" + Thread.CurrentThread.ManagedThreadId);
}
static void t_First(object sender, EventArgs e)
{
Console.WriteLine("- first callback on:" + Thread.CurrentThread.ManagedThreadId);
}
class tt
{
public tt()
{
}
public event EventHandler First;
public event EventHandler Second;
public void Test()
{
Thread.Sleep(1000);
Console.WriteLine("invoked on:" + Thread.CurrentThread.ManagedThreadId);
First(this, null);
Thread.Sleep(1000);
Second(this, null);
}
}
}
As you can probably guess, only the first writeline is executed on the main thread, the other calls are all executed on the new thread created by the task.
I'd like to synchronize the call to "Second" back on the main thread (it should never get called, because i am blocking in the while loop). However i'd like to know the way of doing this or if its even possible?