Note that there are some explanatory texts on larger screens.

plurals
  1. POCreating a WPF Window from a WinForms BackgroundWorker
    primarykey
    data
    text
    <p>I have a WPF dll that contains a number of Window classes and exposes methods that display those windows.</p> <p>I also have a separate WinForms project that is calling one of those methods in the WPF project inside the DoWork method of a BackgroundWorker component.</p> <p>On the line of code that instantiates a WPF Window, I get the following runtime error:</p> <blockquote> <p>The calling thread must be STA, because many UI components require this.</p> </blockquote> <p>A google search let me to <a href="http://www.eggheadcafe.com/conversation.aspx?messageid=31268816&amp;threadid=31268816" rel="nofollow noreferrer">this discussion</a>. (Turns out Jon Skeet answers questions on other sites in addition to Stack Overflow!) He linked to <a href="http://msdn.microsoft.com/en-us/magazine/cc163328.aspx" rel="nofollow noreferrer">this article</a>, which states</p> <blockquote> <p>The BackgroundWorker component works well with WPF ...</p> </blockquote> <p>That article also mentions using the DispatcherObject class, but I don't understand how to make that work and I would rather just continue using my BackgroundWorker component.</p> <p>As a test case, I came up with the following code to reproduce the error. In the WPF class library, here is the code in Window1.xaml.vb</p> <pre><code>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 </code></pre> <p>In the WinForms application, here is the code in Form1.vb</p> <pre><code>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 </code></pre> <p>Even when the BackgroundWorker component is placed in Window1.xaml.vb itself, the same error occurs. So, is that article wrong and I can't really use a BackgroundWorker with WPF? Or is there something else I need to do to get it to work?</p> <p>If the BackgroundWorker won't work, then how would I replace the code in Form1.vb above to use a Dispatcher instead?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload