简体   繁体   中英

Trouble Awaiting Task in UI

The following method, running in the MainWindow code behind in my WPF app, is producing a well-documented StackOverflow error:

        async void LDAPLookupButton_Click(object sender, RoutedEventArgs e)
        {
            input = LDAPInputFileLocationTextBox_Value.Text;

            LDAPProgress.Visibility = Visibility.Visible;
            await Task.Run(() => LDAPLookups.ExportToCSV(input));
            LDAPProgress.Visibility = Visibility.Hidden;
        }

This results in error:

The calling thread must be STA, because many UI components require this.

Adjusting the method per the recommended guidance allows the app to run, but as expected the UI is blocked during execution of the Dispatcher action:

            async void LDAPLookupButton_Click(object sender, RoutedEventArgs e)
            {
                input = LDAPInputFileLocationTextBox_Value.Text;

                LDAPProgress.Visibility = Visibility.Visible;

                Dispatcher.Invoke(() =>
                {
                     LDAPLookups.ExportToCSV(input);
                });

                LDAPProgress.Visibility = Visibility.Hidden;
            }

I have two questions at this point:

  1. Why is the "calling thread must be STA..." error being called when the LDAPLookups.ExportToCSV method is making no updates to the UI? The method runs out of another class and simply creates a .csv on the local machine.

  2. How can I allow this to run while not blocking the UI?

Summay of comment beneath question above


The only reason why I can see this error occurring is if ExportToCSV (remember it is now running in a worker thread and a worker thread may not directly access the UI) is accessing the UI. Is it?

Also, using Dispatcher.Invoke* is kinda pointless for async/await particularly when you are already in a UI callback.

Be sure to check the relevant code.

对于第二个问题,使用 Dispatcher.BeginInvoke() 将被异步调用。

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