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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6719132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 17:27:57  来源:igfitidea点击:

How to make a method run in the "background" (threading?)

c#.netwindowsmultithreading

提问by James

I currently have some code that cycles through a text file looking for a specific phrase. However, when this method runs, the whole application locks up. I assume because it's looping, which is what I want.

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

I would like this to happen in the background, so normal methods and user interaction with the application can still be done.

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

How can this be done/improved?

如何完成/改进?

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);
                }
            }
        }
    }
}

采纳答案by marc

Use

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

or the backgroundworker component from the palette.

或调色板中的后台工作组件。