Using Console.WriteLine in doWork BackgroundWorker event

I have a console application that uses a BackgroundWorker object and wants to test my output using Console.WriteLine (fooBar). However, this application exits because the application executes the Console.WriteLine command.

Here's the version below illustrating 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 that the app seems to come out this way?

+4
source share
3 answers

For your backgroundworker set WorkerReportsProgress to true . Subscribe to the ProgressChanged event as follows:

 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { for (var i = 0; i < 1000; i++) { backgroundWorker1.ReportProgress(i); } } private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { Console.WriteLine(e.ProgressPercentage); } 

If you need to pass more than just int from your background thread to the user interface thread, then you can do something like this:

 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { for (var i = 0; i < 1000; i++) { var myObjectInstance = new MyObject{ ...}; backgroundWorker1.ReportProgress(null, myObjectInstance); } } private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { var myObjectInstance = (MyObject)e.UserState; Console.WriteLine(myObjectInstance); } 
+2
source

The application exits because it actually terminates and no longer needs to be done ;-) After you plan the background worker and start the thread to do this, you must tell the main thread to stop and wait for one thing or the other . A very common way to do this (usually used in test / sample code) is to simply issue Console.ReadKey(); as the very last line of code in your main method. This will make your application wait until you press a key before exiting the process.

+5
source

Perhaps I misunderstood your setting. I assume that you are using a background thread, but the main process exits from it, which causes the thread to stop before it does anything. Perhaps try putting something in your main process that will prevent the main thread from exiting, like Console.ReadKey ();

+2
source

All Articles