0

I've looked around google cause i need to mutithread as my program lags whenever it attempts to load a gif and load a usercontrol at the same time. Rather, the gif hangs and the the page suddenly shows my usercontrol without any transition. Ok How the program is supposed to behave,

Show gif-->Load Usercontrol-->Hide Gif-->run animation(a Simple slide in effect)

But because of the lag when rendering the ui elements of the usercontrol, the program behaves like this

Show Gif -->Gif Hangs(or freezes) -->show Usercontrol immediately

So I found this thing called BackgroundWorker . Sounds great . Well ... not entirely. i tried it out and applied it to my codes like so

        BackgroundWorker worker = new BackgroundWorker();
        CrowdWatch_Portrait.CrowdWatch crowder;
        //The page is a frame fyi
        thePage.LoadCompleted += new LoadCompletedEventHandler(thePage_LoadCompleted);

        worker.DoWork += delegate(object s, DoWorkEventArgs args)
        {

                crowder = new CrowdWatch_Portrait.CrowdWatch();
                thePage.Content = crowder;

        };


        worker.RunWorkerAsync();

Sounds good. Ran it. Failed. It gave me this error

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

So after researching online again , I couldn't find any scenario in which this class was used to load a usercontrol. So I turn to the community for help....help?

H.B.
  • 166,899
  • 29
  • 327
  • 400

2 Answers2

0

I didn't remember exactly why, but in one of my program, I was confronted to the same error. I resolved with this code :

_wakeupthread.SetApartmentState(System.Threading.ApartmentState.STA);

Hope it's help :-)

chrisendymion
  • 175
  • 1
  • 9
  • How do i implement this code? Sorry but im new to mutithreading –  Jul 31 '12 at 06:38
  • Sorry, I was using System.Threading.Thread, not BackgroundWorker.. I don't know how to do this with BackgroundWorker. Try this System.Threading.Thread.CurrentThread.SetApartmentState(ApartmentState.STA); in you Worker.DoWork function. – chrisendymion Jul 31 '12 at 06:54
  • Now i got this error: Failed to set the specified COM apartment state. googling it up now –  Jul 31 '12 at 07:25
  • Have you seen this post : http://stackoverflow.com/questions/10498555/calling-showdialog-in-backgroundworker ? – chrisendymion Jul 31 '12 at 07:39
0

Try setting the page content on the UI dispatcher like this -

App.Current.Dispatcher.BeginInvoke((Action)delegate{ thePage.Content = crowder; });
Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
  • My gif still lags. Any other alternatives ? Im loading a usercontrol that requires rendering not running a long time process –  Aug 01 '12 at 05:45