且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

尝试在Backgroundworker方法中显示报告时出现错误

更新时间:2023-10-22 10:55:28

您无法与后台线程中的UI项进行交互.对任何UI项的所有访问都必须在UI线程(您的应用开始于该线程)上完成.

行(包括SalesReport sreport ...)之后的所有代码都必须在UI线程上运行,而不是在BackgroundWorker中运行.

从此代码块的内容来看,没有理由让其余代码在BackgroundWorker上运行,因此您实际上不需要此代码的后台线程.
You cannot interact with UI items from a background thread. ALL access to ANY UI items must be done on the UI thread (the thread your app started on).

All of the code after and including the SalesReport sreport..." line MUST be run on the UI thread, not in the BackgroundWorker.

Judging by the content of this code block, there''s no reason for the remaining code to be run on a BackgroundWorker, so you really don''t need a background thread for this code.


您不能从未创建Windows UI组件的线程访问Windows UI组件(错误状态).

解决方案是使用委托返回UI线程或使用Progress update或complete事件.我为您推荐了最后一种,因为看来您已经完成了工作线程.
对于需要反馈的长期运行的过程(进度条),更新进度的作用更大.在某些情况下,使用委托是必要的,但这不是其中之一.

这是使用进度更改"事件和/或完成"事件的方式(应该使用完成"事件并将"SalesReport"代码放在此处)

You can not access Windows UI components from a thread that did not create it (as the error states).

The solution is to use a delegate to get back to the UI thread or use the Progress update or complete event. I recommend the last one for you case as it seems you are done with the worker thread.
Updating progress is more for long running process that you want feedback (i.e. progress bar). Using a delegate is necessary in some cases but this is not one of them.

Here is how you use the Progress change event and/or the completion event (you should use the completion event and put the "SalesReport" code there)

BackgroundWorker worker = new BackgroundWorker();

worker.ProgressChanged += worker_ProgressChanged;
worker.WorkerReportsProgress = true; //You need to set this if you require updates or you will get an exception
worker.RunWorkerCompleted += worker_RunWorkerCompleted;

...

void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//This is called after the DoWork method completes
   throw new NotImplementedException();
}

void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    //This is called anytime the worker thread calls "ReportProgress". Note you must have set WokerReportsProgress to true
    throw new NotImplementedException();
}