开发者

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

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
   开发者_StackOverflow社区                 MessageBox.Show(s);
                }
            }
        }
    }
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜