[英]how to start a thread for a period of time
我创建了线程类并启动了该线程。
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();
}
}
}
如何在每个指定的时间段内执行上述方法? 是否可以使用线程。 计时器方法设置启动线程的时间段?
是的,您可以使用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
。
是的,您可以使用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
}
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);
}
}
}
}
希望这会帮助你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.