Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Console.WriteLine in a BackgroundWorker doWork event

I have a console application that utilizes the BackgroundWorker object and wanted to test my output with a Console.WriteLine(fooBar). However, that application exits as the application executes the Console.WriteLine command.

Here's a watered down version that illustrates what I wanted to do:

protected static void bWorker_DoWork(object sender, DoWorkEventArgs e)
{
    for (int i = startId; i <= endId; i++)
    {
        Console.WriteLine(i.ToString());
        Thread.Sleep(1000);
    }
}

Any ideas why the application would appear to exit like that?

like image 646
Andy Evans Avatar asked Dec 28 '22 19:12

Andy Evans


1 Answers

The application exits because it in fact completes execution and has no more work to do ;-) Once you schedule the background worker and kick off the thread to do it's thing, you have to tell the main thread to stop and wait for one thing or another. A very common way of doing this (Generally used in test/sample code) is to simply issue a Console.ReadKey(); as the very last line of code in your main method. This will cause your application to wait until you press a key before exiting the process.

like image 140
Joel Martinez Avatar answered Jan 17 '23 12:01

Joel Martinez