0

I'm really desperate. I have WPF MVVM app and I send and recieve some packets through USB. I use a library for that and this library needs HwndSource. Everything works fine, but now I need to send many packets and it takes some time so I decided that I use BackgroundWorker and show ProgressBar, but I don't know how to use HwndSource in BackgroundWorker, because I got this error:

The calling thread must be STA, because many UI components require this.

Can anyone help me with this issue?
Thank you.

Artholl
  • 1,291
  • 1
  • 19
  • 38

3 Answers3

0

Can you pass the HwndSource from your UI thread to your BackgroundWorker? If so and it doesn't cause any performance issues, that would be easiest. If this causes performance issues, your best bet might be to create your own STA thread and do your work there rather than using BackgroundWorker.

Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
  • Thank you for your quick answer too. I use @Killercam advice. I search for any solution for two days and it seems that make my own thread is the best way how to managed this. – Artholl Apr 12 '12 at 19:39
0

When using seperate threads they need to be in a STA (single-threaded apartment), which is not the case for background worker threads. You will probably have to create the thread yourself as stated in this answer

Thread t = new Thread(ThreadProc); 
t.SetApartmentState(ApartmentState.STA); 
t.Start(); 

with ThreadProc being a delegate of type ThreadStart.

Community
  • 1
  • 1
MoonKnight
  • 23,214
  • 40
  • 145
  • 277
  • Thank you for your quick answer. I already found the article on which you post link. I just wonder if there is some solution with BackgroundWorker. – Artholl Apr 12 '12 at 19:35
0

Sounds like it's working except when you try to update the progress control. In the ProgressChanged event of the BW, if you're trying to update the control directly, you may get the error you're experiencing. Since you're using MVVM, in the ProgreeChanged event you should update the view-model property that's bound to progress control, if you aren't already doing this.

Big Daddy
  • 5,160
  • 5
  • 46
  • 76
  • Thanks for your answer. Problem is with HwndSource. It's throw posted error when I call it. I read something about it [here](http://stackoverflow.com/a/1699709/1108200). I just want to know, if there is better solution than chreate my own thread. – Artholl Apr 12 '12 at 19:45