相关疑难解决方法(0)

主线程的SynchronizationContext.Current如何在Windows窗体应用程序中变为空?

我的应用程序有问题:在某些时候,SynchronizationContext.Current对主线程变为null.我无法在一个孤立的项目中重现同样的问题.我的真实项目很复杂; 它混合使用Windows窗体和WPF并调用WCF Web服务.据我所知,这些都是可以与SynchronizationContext交互的系统.

这是我孤立项目的代码.我真正的应用程序做了类似的事情.但是,在我的实际应用程序中,执行继续任务时,主线程上的SynchronizationContext.Current为null.

private void button2_Click(object sender, EventArgs e)
{
    if (SynchronizationContext.Current == null)
    {
        Debug.Fail("SynchronizationContext.Current is null");
    }

    Task.Factory.StartNew(() =>
    {
        CallWCFWebServiceThatThrowsAnException();
    })
    .ContinueWith((t) =>
    {

        //update the UI
        UpdateGUI(t.Exception);

        if (SynchronizationContext.Current == null)
        {
            Debug.Fail("SynchronizationContext.Current is null");
        }

    }, CancellationToken.None, 
       TaskContinuationOptions.OnlyOnFaulted,
       TaskScheduler.FromCurrentSynchronizationContext());
}
Run Code Online (Sandbox Code Playgroud)

什么可能导致主线程的SynchronizationContext.Current变为null?

编辑:

@Hans要求堆栈跟踪.这里是:


   at MyApp.Framework.UI.Commands.AsyncCommand.HandleTaskError(Task task) in d:\sources\s2\Framework\Sources\UI\Commands\AsyncCommand.cs:line 157
   at System.Threading.Tasks.Task.c__DisplayClassb.b__a(Object obj)
   at System.Threading.Tasks.Task.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
   at System.Threading.Tasks.Task.ExecutionContextCallback(Object obj)
   at System.Threading.ExecutionContext.runTryCode(Object userData)
   at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, …

c# wpf winforms task-parallel-library

40
推荐指数
3
解决办法
2万
查看次数

标签 统计

c# ×1

task-parallel-library ×1

winforms ×1

wpf ×1