Warum SynchronizationContext funktioniert nicht richtig?

Habe ich folgenden 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);
}

Erwarte ich Letzte Methode, die ausgeführt werden, im ersten thread, d.h. der erste thread, in dem Synchronisierungskontext entnommen ist, denn ich nenne Post() Methode in diesen Kontext. I. e. so etwas wie dieses:

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)

Ist es nicht der Sinn des SynchronizationContext? Aber eigentlich habe ich folgende Ausgabe:

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)

Was ist das problem? Macht das etwas schief gehen mit SynchronizationContext-oder habe ich etwas Missverständnis?

Update: ich nenne diese Methode als unit-test mit Resharper test-runner.

  • Sie haben nicht uns gezeigt, wie diese aufgerufen werden, oder was mit der Synchronisation Kontext (z.B. einer WinForms-Ereignis-Schleife). Bitte aktualisieren Sie Ihre Frage mit einem kurzen, aber vollständigen Beispiel.
  • Dies ist unit-test (MS-Test-Framework), ich benutze Resharper unit-test-runner.
InformationsquelleAutor Alex Kofman | 2010-10-08
Schreibe einen Kommentar