SynchronizationContext

SynchronizationContext

对于 .NET 4.0 中的主线程上的 SynchronizationContext.Current 意外为空的问题,有什么解决方法?看:

  • SynchronizationContext.Current is null in Continuation on the main UI thread
  • 最佳答案

    我创建了几个匹配 ContinueWithStartNew 的扩展方法,除了它们还需要一个额外的 SyncronizationContext 。然后我使用这个参数在执行操作之前恢复预期的 SynchronizationContext:

    下面,我举了例子:

    public static class TaskExtensionMethods
    {
        public static Task ContinueWith_UsingSyncContextWorkaround(this Task task, Action<Task> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler, SynchronizationContext sc)
        {
            Action<Task> actionWithWorkaround = t =>
            {
                SynchronizationContext.SetSynchronizationContext(sc);
                continuationAction(t);
            };
    
            return task.ContinueWith(actionWithWorkaround, cancellationToken, continuationOptions, scheduler);
        }
    
        public static Task StartNew_UsingSyncContextWorkaround(this TaskFactory taskFactory, Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler, SynchronizationContext sc)
        {
            Action actionWithWorkaround = () =>
            {
                SynchronizationContext.SetSynchronizationContext(sc);
                action();
            };
    
            return taskFactory.StartNew(actionWithWorkaround, cancellationToken, creationOptions, scheduler);
        }
    }
    

    然后我使用这些扩展方法代替 .ContinueWith.StartNew
    相关问题:
  • How to create a generic Task.ContinueWith extension method
  • 关于c# - .NET 4.0 中 SynchronizationContext.Current 为空的问题的解决方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20953281/

    10-10 14:59