码迷,mamicode.com
首页 > Windows程序 > 详细

C# 中 SetTimeout 方案

时间:2019-12-23 15:20:04      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:timeout   end   tar   response   requested   ons   color   lse   cell   

C# 中 延时执行方案,如下,如果同一个DelayedProcess 对象连续调用 SetTimeout ,默认取消前一次调用.

 public class DelayedProcess<Req,Rsp>
    {
        public delegate void ExcuteMethod(Result rsp);
        CancellationTokenSource tokenSource;

        public class Result {

            public Req request {
                get;
                set;
            }

            public Rsp response {
                get;
                set;
            }

            /// <summary>
            /// 抛出异常信息
            /// </summary>
            public Exception ex;

            /// <summary>
            /// 是否延时执行成功
            /// </summary>
            public bool IsSuccess {
                get;
                set;
            }
        }

        async void TaskDelay(int timeout, CancellationToken token, ExcuteMethod method,  Result rsp)
        {
            try
            {
                await Task.Delay(timeout, token);
                rsp.IsSuccess = true;
                rsp.ex = null;
            }
            catch (Exception ex)
            {
                rsp.ex = ex;
                rsp.IsSuccess = false;
            }
            finally {
                method(rsp);
            }
        }

        public void SetTimeout(int timeout, ExcuteMethod method, Result rsp)
        {
            Cancel();
            tokenSource = new CancellationTokenSource();
            TaskDelay(timeout, tokenSource.Token, method , rsp);
        }

        public void Cancel()
        {
            if (tokenSource != null && !tokenSource.IsCancellationRequested)
            {
                tokenSource.Cancel();
            }
        }
    }

  

调用示例:

  DelayedProcess<string, string> dp = new DelayedProcess<string, string>();

        private void button1_Click(object sender, EventArgs e)
        {
            Console.WriteLine("{0}:{1}", DateTime.Now, "开始请求");
            dp.SetTimeout(2000, (arg) => {
                if (arg.IsSuccess)
                {
                    Console.WriteLine("{0}:延时执行{1}", DateTime.Now, arg.request);
                }
                else {
                    Console.WriteLine("{0}:延时失败,{1}", DateTime.Now, arg.ex.Message);
                }
            }, new DelayedProcess<string, string>.Result() { request = "1111" });
        }

C# 中 SetTimeout 方案

标签:timeout   end   tar   response   requested   ons   color   lse   cell   

原文地址:https://www.cnblogs.com/howtrace/p/12083645.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!