如果您在使用.NET 4中有更好的方法與Tasks
要做到這一點,但假設你需要使用Threads
...
如果你的例子是一個控制檯應用程序,然後在你的主要方法將退出,可能在Go
開始執行之前。所以當引發異常時,你的「主線程」可能不存在。要停止這一點,你需要一些同步。
像這樣的東西應該做的:
static Exception _ThreadException = null;
public static void Main()
{
var t = new Thread (Go);
t.Start();
// this blocks this thread until the worker thread completes
t.Join();
// now see if there was an exception
if (_ThreadException != null) HandleException(_ThreadException);
}
static void HandleException(Exception ex)
{
// this will be run on the main thread
}
static void Go()
{
try
{
// ...
throw null; // The NullReferenceException will get caught below
// ...
}
catch (Exception ex)
{
_ThreadException = ex;
}
}
如果這是一個用戶界面的應用程序,事情更容易一些。您需要將一些對UI線程的引用傳遞給Go
方法,以便知道發送異常的位置。最好的辦法是通過UI線程的SynchronizationContext
。
像這樣的工作:
public static void Main()
{
var ui = SynchronizationContext.Current;
new Thread (() => Go(ui)).Start();
}
static void HandleException(Exception ex)
{
// this will be run on the UI thread
}
static void Go(SynchronizationContext ui)
{
try
{
// ...
throw null; // The NullReferenceException will get caught below
// ...
}
catch (Exception ex)
{
ui.Send(state => HandleException(ex), null);
}
}
C#4.0不可用 – user829174 2012-01-08 11:33:18