首先,同步上下文并不是什么新鲜事,它从 .NET 2.0 开始就存在了。它与异常处理无关特别。它也不会使Control.Invoke 过时。事实上,WinFormsSynchronizationContext 是 WinForms 的同步上下文实现,它使用 Control.BeginInvoke 表示 Post 和 Control.Invoke 表示 Send 方法。
如何处理异常?我注意到有时例外
在“同步/调用”线程上抛出的丢了?
这里的“有时”背后有一个有据可查的行为。 Control.Invoke 是一个同步调用,它将异常从回调内部传播到调用线程:
int Test()
{
throw new InvalidOperationException("Surpise from the UI thread!");
}
void Form_Load(object sender, EventArgs e)
{
// UI thread
ThreadPool.QueueUserWorkItem(x =>
{
// pool thread
try
{
this.Invoke((MethodInvoker)Test);
}
catch (Exception ex)
{
Debug.Print(ex.Message);
}
});
}
使用SynchronizationContext 的好处在于解耦WinForms 细节。这对于可移植库很有意义,它可能被 WinForms、WPF、Windows Phone、Xamarin 或任何其他客户端使用:
// UI thread
var uiSynchronizationContext = System.Threading.SynchronizationContext.Current;
if (uiSynchronizationContext == null)
throw new NullReferenceException("SynchronizationContext.Current");
ThreadPool.QueueUserWorkItem(x =>
{
// pool thread
try
{
uiSynchronizationContext.Send(s => Test(), null);
}
catch (Exception ex)
{
Debug.Print(ex.ToString());
}
});
因此,使用Control.Invoke(或SynchronizationContext.Send),您可以选择处理调用线程上的异常。根据设计和常识,Control.BeginInvoke(或SynchronizationContext.Post)没有这样的选择。这是因为Control.BeginInvoke 是异步的,它会将回调排队,以便在Application.Run 运行的消息循环的未来迭代中执行。
为了能够处理异步回调引发的异常,您需要实际观察异步操作的完成情况。在 C# 5.0 之前,您可以使用事件或 Task.ContinueWith。
使用事件:
class ErrorEventArgs : EventArgs
{
public Exception Exception { get; set; }
}
event EventHandler<ErrorEventArgs> Error = delegate { };
void Form_Load(object sender, EventArgs e)
{
this.Error += (sError, eError) =>
// handle the error on the UI thread
Debug.Print(eError.Exception.ToString());
ThreadPool.QueueUserWorkItem(x =>
{
this.BeginInvoke(new MethodInvoker(() =>
{
try
{
Test();
}
catch (Exception ex)
{
// fire the Error event
this.Error(this, new ErrorEventArgs { Exception = ex });
}
}));
});
}
使用ContinueWith:
ThreadPool.QueueUserWorkItem(x =>
{
var tcs = new TaskCompletionSource<int>();
uiSynchronizationContext.Post(s =>
{
try
{
tcs.SetResult(Test());
}
catch (Exception ex)
{
tcs.SetException(ex);
}
}, null);
// observe the completion,
// only if there's an error
tcs.Task.ContinueWith(task =>
{
// handle the error on a pool thread
Debug.Print(task.Exception.ToString());
}, TaskContinuationOptions.OnlyOnFaulted);
});
最后,在 C# 5.0 中,您可以使用 async/await 并处理异步抛出的异常,与 try/catch 同步调用一样方便:
int Test()
{
throw new InvalidOperationException("Surpise from the UI thread!");
}
async void Form_Load(object sender, EventArgs e)
{
// UI thread
var uiTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
await Task.Run(async () =>
{
// pool thread
try
{
await Task.Factory.StartNew(
() => Test(),
CancellationToken.None,
TaskCreationOptions.None,
uiTaskScheduler);
}
catch (Exception ex)
{
// handle the error on a pool thread
Debug.Print(ex.ToString());
}
});
}