博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

异步等待(ManualResetEvent

Posted on 2015-10-02 16:34  system_kk  阅读(395)  评论(0编辑  收藏  举报

 

ManualResetEvent实现异步等待,超过时间 不做处理,继续往下执行代码

(ManualResetEvent 涉及一个线程在其他线程进行之前必须完成的任务)

 1 ManualResetEvent[] mre = new ManualResetEvent[2];
 2 
 3             mre[0] = new ManualResetEvent(false);
 4             shoppingbll spb = new shoppingbll(mre[0], dict);
 5             Thread thd1 = new Thread(new ThreadStart(spb.GetGPrice));
 6             thd1.Start();
 7 
 8             mre[1] = new ManualResetEvent(false);
 9             farebll pfb = new farebll(mre[1], dict);
10             Thread thd2 = new Thread(new ThreadStart(pfb.GetfarePrice));
11             thd2.Start();
12 
13             //停顿12s 超过12s后,执行后面代码,不再等待
14             WaitHandle.WaitAll(mre, 12000, false);
View Code

 

GetGPrice 方法(GetfarePrice类似) ,调用ManualResetEvent 的set()方法  返回信号;

public void GetGPrice()
        {
            try
            {
                 //todo
            }
            catch (Exception e)
            {

            }
            finally
            {
                if (_mre != null)
                {
                    _mre.Set();//返回完成信号
                }
            }
        }
View Code

 

Task(任务)类似用法:

 1             Task t1 = new Task(func);//无返回值
 2             Task<int> t2 = new Task<int>(()=>canshufun(1));//有返回值(带参数
 3             Task<int> t3 = new Task<int>(() => intfun());//有返回值(无参数           
 4             
 5             Task[] tt = new Task[] { t1, t2 ,t3};
 6             Task.WaitAll(tt, 10 * 1000);//10秒后 不再等待,往后执行
 7             int result2 = t2.Result;//获取返回结果
 8             int result3 = t3.Result;//获取返回结果        
 9 
10 public void func()
11         { }
12 
13         public int intfun()
14         {
15             return 0;
16         }
17         public int canshufun(int i)
18         {
19             return i;
20         }
View Code

 

Task 通过CancellationTokenSource参数 取消超时线程任务 

 1 /// <summary>
 2         /// 返回政策
 3         /// </summary>
 4         /// <param name="dept">出发</param>
 5         /// <param name="arr">到达</param>
 6         /// <param name="depttime">出发日期</param>
 7         /// <param name="arrtime">返程日期</param>
 8         /// <param name="from">政策源</param>
 9         /// <param name="carriers">航司</param>
10         /// <param name="cabinlevels">舱位等级(First, Business, Economy)</param>
11         /// <param name="ftype">1,直飞;2,所有</param>
12         /// <param name="number">返回数量</param>
13         /// <param name="second">超时时间</param>
14         /// <param name="iresponsetime">国际接口返回时间</param>
15         /// <param name="nresponsetime">国内接口返回时间</param>
16         /// <returns></returns>
17         public model.PolicyCacheModel Get(string dept, string arr, string depttime, string arrtime, string from, string carriers, string cabinlevels, string ftype, int number, int second, ref int iresponsetime, ref int nresponsetime)
18         {
19             List<string> policies = from.Split('|').ToList();
20             List<string> gj = new List<string>();
21             List<string> gn = new List<string>();
22             foreach (string s in policies)
23             {
24                 if(s.Contains("12,")) gj.Add(s);
25                 else if (s.Contains("18,")) gj.Add(s);
26                 else if (s.Contains("20,")) gn.Add(s);
27                 else if (s.Contains("50,")) gj.Add(s);
28                 else gn.Add(s);
29             }
30 
31             if (gj.Count == 0 && gn.Count == 0) return null;
32 
33             Task<model.CompareModel> gjtask = null;
34             Task<model.CompareModel> gntask = null;
35             CancellationTokenSource gjct = null;
36             CancellationTokenSource gnct = null;
37             List<Task<model.CompareModel>> tasks = new List<Task<model.CompareModel>>();
38 
39             if (gj.Count > 0)
40             {
41                 gjct = new CancellationTokenSource();
42                 gjtask = new Task<model.CompareModel>(() => GetInternational(dept, arr, depttime, arrtime, from, carriers, cabinlevels, ftype, number, second), gjct.Token);
43                 tasks.Add(gjtask);
44             }
45             if (gn.Count > 0)
46             {
47                 gnct = new CancellationTokenSource();
48                 gntask = new Task<model.CompareModel>(() => GetNational(dept, arr, depttime, arrtime, from, carriers, cabinlevels, ftype, number, second), gnct.Token);
49                 tasks.Add(gntask);
50             }
51 
52             if (gjtask != null) gjtask.Start();
53             if (gntask != null) gntask.Start();
54             Task.WaitAll(tasks.ToArray(), second * 1000);
55 
56             model.CompareModel m1 = null;
57             model.CompareModel m2 = null;
58             if (gjtask != null)
59             {
60                 if (gjtask.Status == TaskStatus.RanToCompletion) m1 = gjtask.Result;
61                 else gjct.Cancel();
62             }
63             if (gntask != null)
64             {
65                 if (gntask.Status == TaskStatus.RanToCompletion) m2 = gntask.Result;
66                 else gnct.Cancel();
67             }
68 
69             try
70             {
71                 model.CompareModel d = InMatch(m1, m2);
72                 model.PolicyCacheModel m3 = MatchRebate(d);
73                 return m3;
74             }
75             catch (Exception ex)
76             {
77                 return null;
78             }
79         }
View Code

 

参考:

http://www.cnblogs.com/li-peng/p/3291306.html

http://www.cnblogs.com/springyangwc/archive/2011/10/12/2208991.html