如何在一段时间内启动一个线程

时间:2014-01-29 12:12:21

标签: c# threadpool

我创建了线程类并启动了该线程。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Thread_class
{
    class Program
    {
        class SubThread
        {
            public void PrintValue()
            {
                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine("Inside PrintValue() of SubThread Class " + i);
                    Thread.Sleep(5);
                }
            }
        }
        static void Main(string[] args)
        {
            SubThread subthread=new SubThread();
            Thread thread = new Thread( new ThreadStart( subthread.PrintValue));
            thread.Start();
             for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine("Inside Main Class " + i);
                    Thread.Sleep(1);

                }
            thread.Join();
        }

    }
}

如何在每个指定的时间段内执行上述方法?是否可以使用线程。 timer方法设置启动线程的时间段?

3 个答案:

答案 0 :(得分:0)

是的,您可以使用Threading.Timer

int timeToStart = 2000;
int period = 1000;

SubThread sub = new SubThread();
Timer timer = new Timer(o => sub.PrintValue(), null, timeToStart, period);

计时器将等待1秒钟,然后每2秒运行一次任务。

您不需要为此创建自己的线程,如果需要,计时器将生成一个线程。 不要忘记在完成后拨打Dispose

答案 1 :(得分:0)

是的,你可以使用System.Threading.Timer,同时注意System.Threading.Timer每次都在ThreadPool的线程中调用回调方法,所以你甚至不需要创建Thread,只需运行定时器,回调将在不同的线程中运行。

致电

Timer t = new Timer(TimerProc, null, startAfter, period);

private void TimerProc(object state)
{
   // This operation will run in the thread from threadpool
}

答案 2 :(得分:0)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Thread_class
{
   class Program
   {

    static void Main(string[] args)
    {
        SubThread subthread = new SubThread();
        Thread thread = new Thread(subthread.PrintValue);
        thread.Start();
        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine("Inside Main Class " + i);
            Thread.Sleep(1);

        }
        thread.Join();
        Console.ReadKey();
    }

}
class SubThread
{
    public void PrintValue()
    {
        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine("Inside PrintValue() of SubThread Class " + i);
            Thread.Sleep(1);
           }
       }
   }
}

希望这会对你有所帮助。

相关问题