views:

613

answers:

1

I have a WindowsForms application wich has SynchronizationContext.Current not null
But from that WindowsForms app I create a new Thread called thread1
From thread1 I create another Thread called thread2
When I try to POST methods from thread2 in thread1 using SynchronizationContext.Current, will fail because SynchronizationContext.Current is null

Please give me a solution to POST a method from thread2 to thread1, but asynchronously

A: 

Because thread1 is in the synchronisation context that will handle the posted message, you need to post using thread1's synchronization context. (Think of the synchronization context as the message receiver.) So you need to pass thread1's synchronization context to thread2 somehow. One way is to pass it as a parameter to thread2 using a ParameterisedThreadStart delegate:

private void Thread2Func(object obj)
{
  SynchronizationContext parentThread = (SynchronizationContext)obj;
  // ...
  parentThread.Post(someCallback, someState);
}

and in thread1:

thread2 = new Thread(Thread2Func);
thread2.Start(SynchronizationContext.Current);
itowlson
but if I'll use the SynchronizationContext from WindowsForm, I think the POST method will POST it to the UI thread, but I want to POST it from thread2 to thread1
pixel3cs
In general, you can't post messages to a thread that hasn't handed over to a synchronisation context such as a message loop or a dispatcher, because the thread has no way of picking the messages up. Depending on your design, you may be able to have thread1 enter a synchronisation context e.g. by calling Dispatcher.Run, or you may have to create your own synchronisation context and write your thread1 code to wait on that context at appropriate times.
itowlson