Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
                    MessageBox.Show(s);
                }
            }
        }
    }
}
like image 666
James Avatar asked Nov 04 '22 18:11

James


1 Answers

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.

like image 196
marc Avatar answered Nov 09 '22 11:11

marc