Using Console.WriteLine in a BackgroundWorker doWork event

旧街凉风 提交于 2019-12-05 13:20:39

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);
}

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.

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();

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!