开发者

Background worker issue

开发者 https://www.devze.com 2023-02-20 19:07 出处:网络
i have a class which, when a certain part of the gui is clicked will -create a backgroundworker and do the following taks

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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消