I have a Windows Forms app that, unfortunately, must make calls to controls from a second thread. I've been using the thread-safe pattern described on the http://msdn.microsoft.com/en-us/library/ms171728.aspx. Which has worked great in the past.
The specific problem I am having now: I have a WebBrowser control and I'm attempting to invoke the WebBrowser.Navigate() method using this Thread-Safe pattern and as a result I am getting StackOverflow exceptions. Here is the Thread-Safe Navigate method I've written.
Private Delegate Sub NavigateControlCallback(ByRef wb As WebBrowser, ByVal url As String)
Private Sub AsyncNavigate(ByRef wb As WebBrowser, ByVal URL As String)
Try
If wb.InvokeRequired Then
Dim callback As New NavigateControlCallback(AddressOf AsyncNavigate)
callback(wb, url)
Else
wb.Navigate(url)
End If
Catch ex As Exception
End Try
End Sub
Is there a Thread-Safe way to interact with WinForms components without the side effect of these StackOverflowExceptions?
This is the problem:
If wb.InvokeRequired Then
Dim callback As New NavigateControlCallback(AddressOf AsyncNavigate)
callback(wb, url)
Else
On the second line of the If block, you're just calling AsyncNavigate again. Directly. Resursively. With no marshalling to a UI thread. You should be using Invoke
or BeginInvoke
:
If wb.InvokeRequired Then
Dim callback As New NavigateControlCallback(AddressOf AsyncNavigate)
wb.BeginInvoke(callback(wb, url))
Else
(Side-note: please don't swallow exceptions like that...)