让我们考虑一种经常更改字符串包含值的方法。 我需要创建每 1 分钟运行一次的线程,以从字符串中获取值。
这可能吗?
我已经尝试了以下代码,它使除特定线程之外的整个进程都处于休眠状态:
System.Threading.Thread.Sleep(10000);
最佳答案
如果您想在定义的时间段运行线程进程,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);
窗体
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);
}
关于c# - 在 c# .net 中运行线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14229239/