c# - 在 c# .net 中运行线程

标签 c# .net multithreading

让我们考虑一种经常更改字符串包含值的方法。 我需要创建每 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/

相关文章:

c# - yield 看不懂的功能

c# - 如何使用 C# 以编程方式运行 ASP.Net 开发服务器?

C# 在构造函数之前执行代码

c# - 将执行的 Sql 保存在表中

java - 线程 hibernate 时间过长

c# - 单独项目中的 MVC 4 管理区域

c# - 应用 CQRS - 是否需要对薄读取层进行单元测试?

c# - 使用 List<> 时使用 ListBox(带有 ItemTemplate)的正确方法

java - volatile 关键字有什么用?

java多线程: traffic intersection system