简体   繁体   中英

creating a UI in background thread WPF?

I tried following:

var task = new Task(() =>
    {
       for (int i=0; i<10; i++) {
          //Create new Grid HERE
          // Add Table with some dynamic data here..
          // print the above Grid here.
        }

    });

task.ContinueWith((previousTask) =>
    {
        label.Content = printerStatus(); // will return "Out of Paper", "printing", "Paper jam", etc.
    },
    TaskScheduler.FromCurrentSynchronizationContext());

label.Content = "Sending to printer";

It returns following error: The calling thread must be STA, because many UI components require this..

The error occurs when it tries to create a new UI object Grid.

How can i fix this? Let me know if there is any other way arround!

Tasks use thread pool threads, which are in a MTA.

If you want a background STA thread, you will have to create one yourself and explicitly set the ApartmentState .

Thread t = new Thread( ... );
t.SetApartmentState( ApartmentState.STA );
t.Start();

Using the Dispatcher for the label and Invoke might help:

label.Dispatcher.Invoke(
      System.Windows.Threading.DispatcherPriority.Normal,
      new Action(
        delegate()
        {
          label.Content = printerStatus();
        }
    ));

You cannot create UI objects on different thread than the main UI thread because as soon as you add them to the UI, it tries to set the Parent property, and a thread in WPF cannot modify objects that were created on a different thread.

Instead, I'd recommend creating a list or collection of the Grid's Data on the 2nd thread, and binding it to the UI using something like an ItemsControl . This will keep all UI objects on the main UI thread, while background processing can be done on a background thread.

To update a UI object from a background thread, such as your status label, I'd recommend using the Dispatcher like lawrencealan's answer suggests. The Dispatcher is WPF's internal message queue for the main UI thread

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