让我们考虑一个经常改变字符串包含值的方法。我需要创建线程,它运行每1分钟从一个字符串中获取一个值。
有可能吗?
我尝试了下面的代码,它会休眠除特定线程之外的整个进程:
System.Threading.Thread.Sleep(10000);发布于 2013-01-09 14:14:50
如果您希望在定义的时间段内运行线程化进程,那么System.Threading.Timer类将是完美的选择
var timer = new System.Threading.Timer((o) =>
{
// do stuff every minute(60000ms)
}, null, 0, 60000);但是,如果要从该线程更新任何UI代码,请不要忘记在UI线程上回调
WPF:
var timer = new System.Threading.Timer((o) =>
{
Dispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate
{
// do stuff WPF UI safe
});
}, null, 0, 60000);Winform
var timer = new System.Threading.Timer((o) =>
{
base.Invoke((Action)delegate
{
// do stuff Winforms UI safe
});
}, null, 0, 60000);示例:
private void StartUpdateTimer()
{
var timer = new System.Threading.Timer((o) =>
{
string ss = "gowtham " + DateTime.Now.ToString();
Response.Write(ss);
}, null, 0,1000);
}发布于 2013-01-09 14:12:31
使用:
new Thread(delegate()
{
while(true)
{
// Do stuff
Thread.sleep(60000);
}
}).Start();60000毫秒是一分钟
Thread.sleep使当前线程进入休眠状态
发布于 2013-01-09 14:19:58
Sleep不会启动新线程,它会在给定的毫秒数内阻塞当前线程(在本例中为UI线程)。
根据您的描述,您希望启动新的线程,并且可以在该线程中休眠。此外,使用计时器可能会更容易。关于MSDN Thread article中线程对象可用性的完整示例和信息
new Thread(ThreadFunction).Start(); https://stackoverflow.com/questions/14229239
复制相似问题