在C#中,處理多線程異常可以通過以下幾種方法:
void WorkerFunction()
{
try
{
// Your code here
}
catch (Exception ex)
{
// Handle exception
}
}
void Main()
{
Thread thread = new Thread(WorkerFunction);
thread.Start();
}
Task task = Task.Factory.StartNew(() =>
{
// Your code here
});
task.ContinueWith(t =>
{
if (t.IsFaulted)
{
// Handle exception
Exception ex = t.Exception;
}
});
Task task = Task.Factory.StartNew(() =>
{
// Your code here
});
try
{
task.Wait();
}
catch (AggregateException ex)
{
foreach (Exception innerEx in ex.InnerExceptions)
{
// Handle exception
}
}
public static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
Application.Run(new MainForm());
}
private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
// Handle exception
Exception ex = e.Exception;
}
請注意,這些方法可能不適用于所有場景,因此在實際應用中,可能需要根據具體情況選擇合適的方法來處理多線程異常。