Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy SynchronizationContext does not work properly?
    primarykey
    data
    text
    <p>I have following code:</p> <pre><code>[TestMethod] public void StartWorkInFirstThread() { if (SynchronizationContext.Current == null) SynchronizationContext.SetSynchronizationContext( new SynchronizationContext()); var syncContext = SynchronizationContext.Current; Console.WriteLine("Start work in the first thread ({0})", Thread.CurrentThread.ManagedThreadId); var action = ((Action) DoSomethingInSecondThread); action.BeginInvoke(CallbackInSecondThread, syncContext); // Continue its own work } private static void DoSomethingInSecondThread() { Console.WriteLine("Do something in the second thread ({0})", Thread.CurrentThread.ManagedThreadId); } private void CallbackInSecondThread(IAsyncResult ar) { Console.WriteLine("Callback in the second thread ({0})", Thread.CurrentThread.ManagedThreadId); var syncContext = (SynchronizationContext) ar.AsyncState; syncContext.Post(CallbackInFirstThread, null); } private void CallbackInFirstThread(object obj) { Console.WriteLine("Callback in the first thread ({0})", Thread.CurrentThread.ManagedThreadId); } </code></pre> <p>I expect last method to be executed in the first thread, i.e. initial thread where SynchronizationContext is taken from, because I call <code>Post()</code> method of this context. I.e. something like this:</p> <pre><code>Start work in the first thread (28) Do something in the second thread (17) Callback in the second thread (17) Callback in the first thread (28) </code></pre> <p>Isn't it the meaning of SynchronizationContext? But actually I have following output:</p> <pre><code>Start work in the first thread (28) Do something in the second thread (17) Callback in the second thread (17) Callback in the first thread (7) </code></pre> <p><strong>What is the problem? Does something go wrong with SynchronizationContext or I have some misunderstanding?</strong></p> <p><strong>Update:</strong> I call this method as a unit test using Resharper test runner.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload