简体   繁体   中英

Dispatcher.InvokeAsync() locks up the GUI until task is finished

I have a control (type DataGrid) that holds large amount of data (up to 1M rows). I implemented a copy-to-clipboard method that dumps the entire contents to the clipboard. This usually takes up to 2 to 3 minutes.

To avoid my users waiting for the process, I'd like to use another thread to process the copy method and return the control back to GUI immediately so the users can proceed with other tasks. When the copy method is complete, then pop up a message box to inform the user.

However, when the code is executed, the GUI gets locked up and does not responds to any user actions until the entire copy method is completed. I wonder where I got it wrong.

Here is the code snappet:

    private void Copy_To_Clipboard()
    {
        this.gridView.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
        DataGridSelectionUnit u = this.gridView.SelectionUnit;
        this.gridView.SelectionUnit = DataGridSelectionUnit.CellOrRowHeader;
        this.gridView.SelectAll();
        ApplicationCommands.Copy.Execute(null, this.gridView);
        this.gridView.UnselectAll();
        this.gridView.SelectionUnit = u;
    }

    private async void cmdClipboard_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("The data is being copied to clipboard. This can take a while as there are " +
            this.NumRecords.ToString("###,###,##0") + " records to be copied. You will be notified when it’s finished",
            "Copy to Clipboard", MessageBoxButton.OK, MessageBoxImage.Information);
        await this.Dispatcher.InvokeAsync((Action)(() =>
        {
            Copy_To_Clipboard();
        }));
        MessageBox.Show("Copy to clipboard is completed.", "Copy to Clipboard", MessageBoxButton.OK, MessageBoxImage.Information);
    }

InvokeAsync doesn't mean "run this code on a background thread"; it means "run this code on the UI thread". Since the code calling InvokeAsync is already on the UI thread, that call does exactly nothing helpful.

The problem is that UI operations must run on the UI thread. This includes reading all the grid values and writing to the clipboard (which is considered a UI object on Windows).

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