简体   繁体   中英

Accessing the UI thread for Windows Forms after background worker?

For my windows forms application, it is a subscriber of a wcf service and i uses a background worker class to do the subscribing codes so that when i click the "subscribe" button, the UI doesn't hang while it attempts to connect to the service.

After using background worker for connection, when it receives a posting from the publisher, it seems that it is unable to access the UI thread even after the following code is used.

The following implementation was done on a postReceived() method that was created on the service and it handles what happens whenever the subscriber does when a posting is posted by the publisher (WCF Publish Subscribe)

        backgroundForm b = (backgroundForm)Application.OpenForms[0];

        b.BeginInvoke((MethodInvoker)delegate()
        {
            //codes to do whatever i wan to do with the GUI
            //Examples of it would be disposing a flowlayout panel 
            //and re-adding it back and populating it again to 
            //show the refreshed values.
        });

anyone has any idea how to solve this?

EDIT

other then the UI code not executed, i also made it a point that whenever a posting is receives, it also displays a tempForm that acts as a popup to the user for the feedback which goes

            notificationForm tempForm = (notificationForm)notificationList[notificationList.Count - 1];
            tempForm.Show();

The above code was also not executed.

You'll have to use the System.Windows.Threading.Dispatcher to access the UI.

Try something like this:

 b.BeginInvoke((MethodInvoker)delegate()
 {
    Dispatcher.Current.Invoke((Action)(DoTheUiThings());
 });

Actually you can call WCF service asyncronously without use of backgroundWorker . Check answers from this thread for that.

The next question you should ask yourself: "Are you sure that Application.OpenForms[0] is your calling form?"

And finally I wonder why you are using BeginInvoke instead of simpler Invoke() method for updating form UI elements. That shouldn't be a long-running operation.

Mayne I didn't understand something in your code - please specify more precise what error or problem are you having.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM