asddasd

导航

c# 超时处理

一:https://www.cnblogs.com/dayang12525/p/10247537.html

        private static bool ImportTaskTimeout(Action method, int hours)
        {
            try
            {
                var task = Task.Run(() => method());
                if (task.Wait(TimeSpan.FromHours(hours)))
                    return task.IsCompleted;
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }


 

static void Main(string[] args)
        {
            Task t = Task.Run(() => {
                Random rnd = new Random();
                long sum = 0;
                int n = 5000000;
                for (int ctr = 1; ctr <= n; ctr++)
                {
                    int number = rnd.Next(0, 101);
                    sum += number;
                    Console.WriteLine("ctr:    {0:N0}", ctr);
                }
            });
            TimeSpan ts = TimeSpan.FromMilliseconds(150);
            if (!t.Wait(ts))
                Console.WriteLine("The timeout interval elapsed.");
        }



二、


Task.Factory.StartNew(() =>
{

//方法/函数/事件
//while (true)
//{
//Thread.Sleep(100);
//string msg = richTextRecv.Text.ToString().Replace("\n", " ");
//if (msg.Contains("succeed"))
//{
//richTextRecv.Text = "";
//break;
//}
//}
}).Wait(1000);

posted on 2020-06-16 21:49  asddasd  阅读(449)  评论(0编辑  收藏  举报