问题
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?
回答1:
For your backgroundworker
set WorkerReportsProgress
to true
. Subscribe to ProgressChanged
event like this:
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 transfer more than just int from your background thread to UI thread, then you could 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:
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.
回答3:
I might not be understanding your setup correctly. I'm guessing that you're running the background thread, but the main process is exiting which causes the thread to be stopped before it gets to do anything. Maybe try putting something in your main process that prevents the main thread from exiting like Console.ReadKey();
来源:https://stackoverflow.com/questions/6165759/using-console-writeline-in-a-backgroundworker-dowork-event