1使用Task
public Form1() { InitializeComponent(); Init(); } private void Init() { Task<int> task = new Task<int>(test); task.ContinueWith(Handler, TaskContinuationOptions.OnlyOnFaulted); task.Start(); } private void Handler(Task<int> obj) { string id=("In handler thread ,id is " + Thread.CurrentThread.ManagedThreadId); var exception = obj.Exception; MessageBox.Show($"With thread id {id}, exception: {exception}"); } private int test() { Console.WriteLine("In test thread ,id is " + Thread.CurrentThread.ManagedThreadId); throw new NotImplementedException(); }
输出:控制台输出
In test thread ,id is 3
消息框输出:in handler Thread id is4