【问题标题】:How to make a method run in the "background" (threading?)如何使方法在“后台”(线程?)
【发布时间】:2023-04-03 11:05:02
【问题描述】:

我目前有一些代码在文本文件中循环查找特定短语。但是,当此方法运行时,整个应用程序都会锁定。我假设因为它是循环的,这就是我想要的。

我希望这发生在后台,所以正常的方法和用户与应用程序的交互仍然可以完成。

如何做到/改进?

private void CheckLog()
{   
    while (true)
    {
        // lets get a break
        Thread.Sleep(5000); 

        if (!File.Exists("Command.bat"))
        {
            continue;
        }

        using (StreamReader sr = File.OpenText("Command.bat"))
        {
            string s = "";

            while ((s = sr.ReadLine()) != null)
            {
                if (s.Contains("mp4:production/"))
                {
                    // output it
                    MessageBox.Show(s);
                }
            }
        }
    }
}

【问题讨论】:

标签: c# .net windows multithreading


【解决方案1】:

使用

class Foo {
    private Thread thread;
    private void CheckLog() {...}
    private void StartObserving() {
        thread = new Thread(this.CheckLog);
        thread.Start();
    }
}

或调色板中的 backgroundworker 组件。

【讨论】:

    猜你喜欢
    • 2012-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 2014-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多