Background worker issue

北战南征 提交于 2019-12-12 04:19:51

问题


i have a class which, when a certain part of the gui is clicked will

-create a backgroundworker and do the following taks

-create a new object(this is a new windows form)

-call a method on it which gets some data

-populate the new windows form gui with that data

The problem is there is a gui component on the form which cant be created from outside of the main programme thread, if i do try i get the error

Active x .... cannot be instantiated because the current thread is not in a single-threaded apartment.

is there help people can offer so i can structure this?

in my do work


回答1:


Don't create GUI components in a background thread. Use the background thread to get and process data, then render them in the UI in the main thread. I know that this in inconvenient, because

  • creating lots of UI elements can also take a lot of time and
  • creating them in the UI thread requires you to split your code into UI part and data processing part,

but there's not really a way around it. .NET UI components are not designed to be handled in background threads.

To perform only certain operations of your code in the main thread, you can use

  • someUIControl.Invoke(...) (WinForms) or
  • Dispatcher.Invoke(...) (WPF)

in the DoWork event handler of your BackgroundWorker. Alternatively, you can perform the UI operations in the RunWorkerCompleted event handler of your BackgroundWorker, which always executes in the UI thread.




回答2:


The UI should only be managed by the UI thread.

One possible solution would be to load the data asynchronously with the BackgroundWorker, and when it is done use the Result property of the DoWorkEventArgs to pass the results back to the UI thread and then display the new form.



来源:https://stackoverflow.com/questions/5497796/background-worker-issue

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