在c#.net中运行线程

Gow*_*nSS 1 .net c# multithreading

让我们考虑一个经常更改字符串包含值的方法.我需要创建一个每1分钟运行一次的线程来获取字符串中的值.

可能吗?

我已经尝试了以下代码,这些代码会在整个进程中休眠该特定线程:

System.Threading.Thread.Sleep(10000);
Run Code Online (Sandbox Code Playgroud)

sa_*_*213 5

如果你想在规定的时间内运行一个线程进程,那么这个System.Threading.Timer类将是完美的

var timer = new System.Threading.Timer((o) =>
{
    // do stuff every minute(60000ms)

}, null, 0, 60000);
Run Code Online (Sandbox Code Playgroud)

但是,如果要从此线程更新任何UI代码,请不要忘记在UI线程上重新调用

WPF:

var timer = new System.Threading.Timer((o) =>
{
    Dispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate
    {
        // do stuff WPF UI safe
    });

}, null, 0, 60000);
Run Code Online (Sandbox Code Playgroud)

Winform的

var timer = new System.Threading.Timer((o) =>
{
    base.Invoke((Action)delegate
    {
        // do stuff Winforms UI safe
    });

}, null, 0, 60000);
Run Code Online (Sandbox Code Playgroud)

例:

private void StartUpdateTimer()
{
    var timer = new System.Threading.Timer((o) => 
    { 
        string ss = "gowtham " + DateTime.Now.ToString(); 
        Response.Write(ss); 
    }, null, 0,1000);
}
Run Code Online (Sandbox Code Playgroud)