How can I create WPF controls in a background thread?

后端 未结 8 612
终归单人心
终归单人心 2021-01-17 15:49

I have method which create background thread to make some action. In this background thread I create object. But this object while creating in runtime give me an exception :

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-17 16:20

    To make your code simply work, you must join a STA COM apartment by calling Thread.SetApartmentState(ApartmentState.STA). Since BackgroundWorker is probably using some shared thread pool, joining a particular apartment may affect other users of this thread pool or may even fail if it has already been set to e.g. MTA before. Even if it all worked out, your newly created TreeView would be locked to this worker thread. You wouldn't be able to use it in your main UI thread.

    If you explained in a bit more detail about your true intentions, you would surely get better help.

提交回复
热议问题