Racoon
Racoon

Reputation: 1011

C# Windows Form Application : how to do something in background after the form has been loaded?

In my Windows Form Application, I successfully run the form:

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());

It works. I have the form loaded.

But if I do something in a cycle after the form has been loaded, say ...

String MyLog = Directory.GetCurrentDirectory() + "\\MyLog.txt";

while (true)
{
                using (StreamWriter writer = new StreamWriter(MyLog, true))
                {
                    writer.Write("Hello");
                }
                Thread.Sleep(1000);
}

... the form is getting closed/crashed.

I tried to specify a special event handler in the Load property of the form but it didn't help:

This piece of code works (I have a string "Hello" written and the form is alive):

private void formLoad(object sender, EventArgs e)
    {
          String MyLog = Directory.GetCurrentDirectory() + "\\MyLog.txt";


                    using (StreamWriter writer = new StreamWriter(MyLog, true))
                    {
                        writer.Write("Hello");
                    }
                    Thread.Sleep(1000);

    }

This piece of code doesn't work (I added a cycle) - the form is crashed:

   private void formLoad(object sender, EventArgs e)
    {
          String MyLog = Directory.GetCurrentDirectory() + "\\MyLog.txt";

          while (true)
          {
                    using (StreamWriter writer = new StreamWriter(MyLog, true))
                    {
                        writer.Write("Hello");
                    }
                    Thread.Sleep(1000);
          }

    }

My question is how can I organize a code so that I can do something in the background after the form is loaded?

Upvotes: 1

Views: 2066

Answers (2)

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

If you wanted to do something like this you could use the BackgroundWorker. But there are some things you need to know. Firstly, to set it up, you need a private class variable and you need to put some code in the constructor:

private BackgroundWorker _worker = new BackgroundWorker();

::ctor
{
    _worker.DoWork += DoBackgroundWork;

    // we set this so you can cancel softly if necessary
    _worker.WorkerSupportsCancellation = true;
}

then you need to define the DoWork handler:

private void DoBackgroundWork(object sender, DoWorkEventArgs e)
{
    String MyLog = Directory.GetCurrentDirectory() + "\\MyLog.txt";

    while (!_worker.CancellationPending)
    {
        using (StreamWriter writer = new StreamWriter(MyLog, true))
        {
            writer.Write("Hello");
        }
        Thread.Sleep(1000);
    }
}

and notice I'm checked the CancellationPending property to ensure we exit gracefully if necessary. Later on, if you need to (e.g. when you close the form), call this:

_worker.CancelAsync();

to shut it down.

Finally, to start it up, call this:

_worker.RunWorkerAsync();

Upvotes: 3

Lloyd
Lloyd

Reputation: 29668

Look at BackgroundWorker component it was specifically designed to allow you to do work in the background and report progress/change to the UI.

Note that you're also pausing the UI thread by calling Thread.Sleep(1000) which probably won't end well.

You can find documentation on background workers here - http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

Upvotes: 2

Related Questions