多线程处理异常:最好在线程内部记录try catch 并且记录错误信息
线程取消:CancellationTokenSource cts类里面实现 cts.Cancel();取消线程
try { CancellationTokenSource cts = new CancellationTokenSource(); List<Task> taskList = new List<Task>(); for (int i = 0; i < 50; i++) { string name = $"btnThreadCore_Click_{i}"; taskList.Add(Task.Run(() => { try { if (!cts.IsCancellationRequested) Console.WriteLine($"This is {name} 开始 ThreadId={Thread.CurrentThread.ManagedThreadId.ToString("00")}"); Thread.Sleep(new Random().Next(50, 100)); if (name.Equals("btnThreadCore_Click_11")) { throw new Exception("btnThreadCore_Click_11异常"); } else if (name.Equals("btnThreadCore_Click_12")) { throw new Exception("btnThreadCore_Click_12异常"); } else if (name.Equals("btnThreadCore_Click_13")) { cts.Cancel(); } if (!cts.IsCancellationRequested) { Console.WriteLine($"This is {name}成功结束 ThreadId={Thread.CurrentThread.ManagedThreadId.ToString("00")}"); } else { Console.WriteLine($"This is {name}中途停止 ThreadId={Thread.CurrentThread.ManagedThreadId.ToString("00")}"); return; } } catch (Exception ex) { Console.WriteLine(ex.Message); cts.Cancel(); } }, cts.Token)); } //1 准备cts 2 try-catch-cancel 3 Action要随时判断IsCancellationRequested //尽快停止,肯定有延迟,在判断环节才会结束 Task.WaitAll(taskList.ToArray()); //如果线程还没启动,能不能就别启动了? //1 启动线程传递Token 2 异常抓取 //在Cancel时还没有启动的任务,就不启动了;也是抛异常,cts.Token.ThrowIfCancellationRequested } catch (AggregateException aex) { foreach (var exception in aex.InnerExceptions) { Console.WriteLine(exception.Message); } } catch (Exception ex) { Console.WriteLine(ex.Message); }
线程零时变量
for (int i = 0; i < 5; i++) { int k = i; Task.Run(() => { Console.WriteLine($"This is btnThreadCore_Click_{i}_{k} ThreadId={Thread.CurrentThread.ManagedThreadId.ToString("00")}"); }); }
线程安全Look 全局零时变量吧多线程变成单线程处理
for (int i = 0; i < 10000; i++)
{
Task.Run(() =>
{
lock (Form_Lock)//任意时刻只有一个线程能进入方法块儿,这不就变成了单线程
{
this.iNumAsync++;
}
});
}