Warum wurde "SwitchTo" aus Async CTP / Release entfernt?

Ich habe heute versucht, mit der SwitchTo-Methode zum GUI-Thread zu wechseln, und festgestellt, dass das Beispiel, von dem ich es aufgehoben habe, nicht funktioniert, einfach weil die Methode nicht vorhanden ist.

Ich fand dann diesen KlappentextHier:

Der Grund, warum wir es losgeworden sind, war, dass es so gefährlich war. Die Alternative besteht darin, Ihren Code in TaskEx.Run zu bündeln ...

Meine Frage ist einfach:Warum war es gefährlich Zu welchen spezifischen Gefahren würde die Verwendung führen?

Beachten Sie, dass ichtat Lesen Sie den Rest dieses Beitrags, damit ich verstehe, dass es hier technische Einschränkungen gibt. Meine Frage ist immer noch, wenn ich mir dessen bewusst bin, warum ist es das?gefährlich?

Ich denke darüber nach, Hilfsmethoden neu zu implementieren, um mir die angegebene Funktionalität zu geben, aber wenn etwas grundlegend kaputt ist, außer dass jemand entschieden hat, dass es gefährlich ist, würde ich es nicht tun.

Ganz naiv würde ich hier die Implementierung der erforderlichen Methoden in Betracht ziehen:

public static class ContextSwitcher
{
    public static ThreadPoolContextSwitcher SwitchToThreadPool()
    {
        return new ThreadPoolContextSwitcher();
    }

    public static SynchronizationContextSwitcher SwitchTo(this SynchronizationContext synchronizationContext)
    {
        return new SynchronizationContextSwitcher(synchronizationContext);
    }
}

public class SynchronizationContextSwitcher : INotifyCompletion
{
    private readonly SynchronizationContext _SynchronizationContext;

    public SynchronizationContextSwitcher(SynchronizationContext synchronizationContext)
    {
        _SynchronizationContext = synchronizationContext;
    }

    public SynchronizationContextSwitcher GetAwaiter()
    {
        return this;
    }

    public bool IsCompleted
    {
        get
        {
            return false;
        }
    }

    public void OnCompleted(Action action)
    {
        _SynchronizationContext.Post(_ => action(), null);
    }

    public void GetResult()
    {
    }
}

public class ThreadPoolContextSwitcher : INotifyCompletion
{
    public ThreadPoolContextSwitcher GetAwaiter()
    {
        return this;
    }

    public bool IsCompleted
    {
        get
        {
            return false;
        }
    }

    public void OnCompleted(Action action)
    {
        ThreadPool.QueueUserWorkItem(_ => action(), null);
    }

    public void GetResult()
    {
    }
}

Dies würde es mir ermöglichen, Code wie folgt zu schreiben:

public async void Test()
{
    await ContextSwitcher.SwitchToThreadPool(); // ensure we're not bogging down the UI thread
    // do some heavy processing
    await _UIContext.SwitchTo(); // presumably saved from the main thread
    // update UI with new data
}

Antworten auf die Frage(2)

Ihre Antwort auf die Frage