如何使方法在“后台”中运行(线程?)

Jam*_*mes 5 .net c# windows multithreading

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

我希望这种情况在后台发生,因此常规方法和用户与应用程序的交互仍然可以完成。

如何做到/改善呢?

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);
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

mar*_*arc 2

使用

class Foo {
    private Thread thread;
    private void CheckLog() {...}
    private void StartObserving() {
        thread = new Thread(this.CheckLog);
        thread.Start();
    }
}
Run Code Online (Sandbox Code Playgroud)

或调色板中的backgroundworker 组件。