-1

In creating jpg images, this code uses threading. However, the Thread.Join() sometimes hangs on creating particular images. I have researched, and it seems as if I should be using BeginInvoke() instead. How could I rewrite the following code from using Thread.Join() to BeginInvoke()?

public Bitmap Generate()
{
    var m_thread = new Thread(_Generate);
    m_thread.SetApartmentState(ApartmentState.STA);
    m_thread.Start();
    m_thread.Join();

    return m_Bitmap;
}

private void _Generate()
{
   var browser = new WebBrowser {ScrollBarsEnabled = false };
   browser.ScriptErrorsSuppressed = true;
   browser.Navigate(m_Url);
   browser.DocumentCompleted += WebBrowser_DocumentCompleted;

   while (browser.ReadyState != WebBrowserReadyState.Complete)
   {
       Application.DoEvents();
   }
   browser.Dispose();
}
Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
Sharma
  • 55
  • 1
  • 7
  • 2
    possible duplicate of [WebBrowser Control in a new thread](http://stackoverflow.com/questions/4269800/webbrowser-control-in-a-new-thread) – Blorgbeard Feb 11 '15 at 03:25

1 Answers1

1

Looking at your code I see one issue. You've registered to the DocumentCompleted event after the Navigate() call. So theoretically it's possible that the event have been fired before you've registered your handler. Try to swap the two lines and see whether you get your problem fixed. I believe that'll be the case if the image has already been retrieved and was cached.

Artak
  • 2,819
  • 20
  • 31
  • Thank you. I appreciate your help. This did not resolve the issue. – Sharma Feb 12 '15 at 03:02
  • So you said the issue can be reproduced for specific images, right ?If so, does the problem reproes, when you call the Generate for just one of those images ? – Artak Feb 12 '15 at 03:43
  • I researched this issue some more, and it seems that I was having some memory and caching issues. I got the code to successfully work now. Thank you. – Sharma Feb 27 '15 at 12:29