随笔- 60  文章- 14  评论- 17 
主线程调用异步服务后,通过设定主线程的等待时间来进行超时处理。
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

 AsyncTaskTest.cs

 

 1 using Microsoft.VisualStudio.TestTools.UnitTesting;
 2 using MyCSharp.Grammas;
 3 
 4 namespace MyCSharp.FunctionTests
 5 {
 6     [TestClass]
 7     public class AsyncTaskTest
 8     {
 9         [TestMethod]
10         public void ExecuteTest_LessThanResponseTime_TimeOut()
11         {
12             var result = new AsyncTask(50).Execute();
13             Assert.IsFalse(result);
14         }
15 
16         [TestMethod]
17         public void ExecuteTest_EqualsResponseTime_Success()
18         {
19             var result = new AsyncTask(100).Execute();
20             Assert.IsFalse(result);
21         }
22 
23         [TestMethod]
24         public void ExecuteTest_MoreThanResponseTime_Success()
25         {
26             var result = new AsyncTask(120).Execute();
27             Assert.IsTrue(result);
28         }
29     }
30 }
View Code

 DemoService.cs

 1 using System.Threading;
 2 
 3 namespace MyCSharp.ExternalService
 4 {
 5     public class DemoService
 6     {
 7         /// <summary>
 8         /// 服务响应
 9         /// </summary>
10         public void Response()
11         {
12             Thread.Sleep(100);
13         }
14     }
15 }
View Code

 

 posted on 2016-06-15 16:32  heoo  阅读(...)  评论(...编辑  收藏