1 tokenSource = new CancellationTokenSource();
2 totalprocesstask = Task.Run( () => {
3 if (isfirst)
4 {
5 TotalTestThreadFunc(isfirst, tokenSource);
6 }
7 else
8 {
9 while (!tokenSource.IsCancellationRequested)//判断任务是否被取消
10 {
11 TotalTestThreadFunc(isfirst, tokenSource);
12 }
13 }
14
15 }, tokenSource.Token);
16
17 //bool res = totalprocesstask.Result;//返回任务结果
18 //单任务结束
19 totalprocesstask.ContinueWith((last) =>
20 {
21 tokenSource.Cancel();//任务取消
22 BindResultData(PredicateBuilder.True<SunnyResult>());
23 ProcessColorEvent(0, "Stop");
24 });//等待任务完成之后任务回调
25
26 //多任务结束
27 //TaskFactory taskFactory = new TaskFactory();
28 //taskFactory.ContinueWhenAll(tasks.ToArray(), t => { Console.WriteLine($"项目经理发布,测试人员测试任务 id:{Thread.CurrentThread.ManagedThreadId} time:{DateTime.Now}"); });
29
30 //异常处理
31 try
32 {
33 totalprocesstask.Wait();//等待完成
34 }
35 catch (Exception ex)
36 {
37 Console.WriteLine(ex.Message);
38 }
39 finally
40 {
41 tokenSource.Dispose();
42 }
43
44
45
46 sfirst = false;
47 bool result = true;
48
49 try
50 {
51 //开启事务
52 _unitOfWork.BeginTran();
53
54 /////////////////////////////////////////for循环判断是否取消
55 if (cancellation.Token.IsCancellationRequested)
56 {
57 Console.WriteLine($"任务已取消 index:{i} id:{Thread.CurrentThread.ManagedThreadId} ");
58 cancellation.Token.ThrowIfCancellationRequested();
59 }
60 _sunnyResultServices.UpdateInSplit(DateTime.Now, it => new SunnyResult()
61 {
62 timeSpan = watch.ElapsedMilliseconds,
63 deviceType = Model.Enums.GlobalEnumVars.ControlDeviceTypes.Camera,
64 createTime = DateTime.Now,
65 resultParams = dic.Count == 0 ? null : JsonConvert.SerializeObject(dic.Select(key => new { x = key.Key, y = key.Value["result"] }).ToDictionary(x => x.x, x => x.y)).Replace("\"", "").Replace(",", " , ").Replace("{", "").Replace("}", "").Replace('"', ' ').Trim(),
66 NGParams = dic.Count == 0 ? null : JsonConvert.SerializeObject(dic.Select(key => new { x = key.Key, y = key.Value["NG"] }).ToDictionary(x => x.x, x => x.y)).Replace("\"", "").Replace(",", " , ").Replace("{", "").Replace("}", "").Replace('"', ' ').Trim(),
67 result = result
68 }, p => p.guid == resultid);
69
70 _unitOfWork.CommitTran();
71 }
72 catch (Exception error)
73 {
74 _unitOfWork.RollbackTran();
75 LogHelper.Log(NLog.LogLevel.Error, this.GetType().FullName, System.Reflection.MethodBase.GetCurrentMethod().Name, error.ToString());
76
77 }