主线程调用异步服务后,通过设定主线程的等待时间来进行超时处理。
Demo如下:

 

AsyncTask.cs 

 

 1 using System;
 2 using System.Threading.Tasks;
 3 using MyCSharp.ExternalService;
 4 
 5 namespace MyCSharp.Grammas
 6 {
 7     public class AsyncTask
 8     {
 9         private readonly int _timeout;
10 
11         private AsyncTask()
12         {
13         }
14 
15         /// <summary>
16         /// 构造函数
17         /// </summary>
18         /// <param name="timeout">超时时间</param>
19         public AsyncTask(Int32 timeout = 30000)
20         {
21             _timeout = timeout;
22         }
23 
24         /// <summary>
25         /// 执行任务
26         /// </summary>
27         /// <returns></returns>
28         public bool Execute()
29         {
30             var task = Task.Factory.StartNew(this.CallExternalSevice);
31             return task.Wait(_timeout);
32 
33         }
34 
35         /// <summary>
36         /// 调用外部服务
37         /// </summary>
38         private void CallExternalSevice()
39         {
40             new DemoService().Response();
41         }
42 
43 
44     }
45 }
View Code

相关文章:

  • 2021-07-18
  • 2021-07-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-15
  • 2022-12-23
  • 2022-12-23
  • 2021-11-30
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-05-26
  • 2022-12-23
  • 2022-03-06
  • 2022-12-23
  • 2021-11-21
相关资源
相似解决方案