并发同事.
我需要能够捕获可能从后台线程抛出的异常.
让代码说明一下(这是一个糟糕的代码)
public delegate bool CheckForUpdatesHandler(Uri uri);
public class UpdatesChecker {
public event AsyncCompletedEventHandler CheckForUpdatesAsyncCompleted;
protected virtual void OnCheckForUpdatesAsyncCompleted(AsyncCompletedEventArgs args) {
if (CheckForUpdatesAsyncCompleted != null)
CheckForUpdatesAsyncCompleted(this, args);
}
public bool CheckForUpdates(Uri ftp) {
Thread.Sleep(1000);
throw new Exception("bla");
return true;
}
public void CheckForUpdatesAsync(Uri ftp){
var action = new CheckForUpdatesHandler(CheckForUpdates);
var c=action.BeginInvoke(ftp, delegate(IAsyncResult state) {
OnCheckForUpdatesAsyncCompleted(new AsyncCompletedEventArgs(null, false, null));
}, null);
}
}
Run Code Online (Sandbox Code Playgroud)
使用Delegate.BeginInvoke,将通过调用.EndInvoke来检索异常 - 您必须执行此操作以防止泄漏.
使用BackgroundWorker,它将出现在完成事件中
在一个香草上Thread,一个未经处理的例外将推翻这个过程.
然而,最简单的方法是:不要让它扔...
public bool CheckForUpdates(Uri ftp) {
try {
Thread.Sleep(1000);
throw new Exception("bla");
return true;
} catch (Exception ex) {
// raise an event, call a method/callback, do something
}
}
Run Code Online (Sandbox Code Playgroud)
如果您当前没有使用EndInvoke,那么可能切换到上面的模式并直接使用ThreadPool(而不是Delegate.BeginInvoke).