I have a WPF dll that contains several Window classes and provides methods that display these windows.
I also have a separate WinForms project that calls one of these methods in a WPF project inside the DoWork method of the BackgroundWorker component.
In the line of code creating the WPF window, I get the following runtime error:
The calling thread must be an STA, because it requires many user interface components.
A google search allows me this discussion . (It turns out that John Skeet answers questions on other sites in addition to stack overflows!) He contacted this article , which says
The BackgroundWorker component works well with WPF ...
This article also mentions the use of the DispatcherObject class, but I don’t understand how to do this, and I would rather just continue to use my BackgroundWorker component.
As a test case, I cited the following code to reproduce the error. In the WPF class library, here is the code in Window1.xaml.vb
Partial Public Class Window1
Public Shared Function ShowMe() As Boolean?
Dim w = New Window1 'Error appears on this line.
Return w.ShowDialog()
End Function
End Class
In a WinForms application, here is the code in Form1.vb
Imports System.ComponentModel
Public Class Form1
Private WithEvents worker As BackgroundWorker
Private Sub doWord(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles worker.DoWork
WpfLibrary.Window1.ShowMe()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
worker = New BackgroundWorker
worker.RunWorkerAsync()
End Sub
End Class
Even when the BackgroundWorker component is placed in Window1.xaml.vb, the same error occurs. So this article is wrong and I can not use BackgroundWorker with WPF? Or is there something else I need to do to make it work?
If BackgroundWorker will not work, how can I replace the code in Form1.vb above to use the dispatcher instead?