您的位置:首页 > 编程语言 > C#

C# 如何让 多线程中每个线程间隔毫秒执行同一个方法

2015-04-24 12:34 661 查看
原文:http://bbs.csdn.net/topics/391020219#post-399131587

class Program
    {
        static int dur = 200;
        static string tm = "";
        static void Main(string[] args)
        {
            for (int i = 0; i < 10; i++)
            {
                var td = new Thread(new ThreadStart(
                () =>
                {
                    lock (tm)
                    {
                        if (tm == "")
                        {
                            Thread.Sleep(dur);
                        }
                        else
                        {
                            var t=DateTime.Now.Subtract(DateTime.Parse(tm));
                            Thread.Sleep(dur - (int)t.TotalSeconds);
                        }
                    };
                    DoSomeThing();
                }
                    ));
                td.Start();
            }
            Console.Read();
        }
 
        private static void DoSomeThing()
        {
            tm = DateTime.Now.ToShortTimeString();
            string info = string.Format("线程ID:{0},执行时间:{1}"
              , Thread.CurrentThread.Name, DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss:ffff"));
            Console.WriteLine(info);
            Thread.Sleep(5000);
        }
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐