简体   繁体   中英

Binding Fails when Calling From Background Thread

Hello I am having some trouble with updating a binding from a background thread. I am displaying an IsBusy indicator while some background processing goes on, then hiding the indicator when finished.

Notice if I set IsLoading to false inside of my background worker (but by invoking it on the UI thread) it doesn't ever update the UI.

If I call it immediately after, on the UI thread. It works.

What am I missing?

        private void BeginValidation()
    {
        m_ValidationWorker = new BackgroundWorker();

        m_ValidationWorker.WorkerReportsProgress = false;
        m_ValidationWorker.DoWork += (_sender, _args) =>
        {
            foreach (DataRecord record in DatabaseViewModel.Instance.Records)
            {
                record.Init();

                Application.Current.Dispatcher.Invoke(()=> { record.IsLoading = false; }); //THIS DOESN'T WORK
            }
        };

        m_ValidationWorker.RunWorkerCompleted += (_sender, _args) =>
        {
            foreach (DataRecord record in DatabaseViewModel.Instance.Records)
            {
             record.IsLoading = false;//THIS WORKS
            }
        };

        m_ValidationWorker.RunWorkerAsync();
    }

And the xaml just for information.

            <telerik:RadBusyIndicator IsBusy="{Binding FirstRecord.IsLoading}" IsIndeterminate="True" DisplayAfter="0" BusyContent="Processing" Style="{StaticResource RadBusyIndicatorStyle}">
            <Grid>
                    <ScrollViewer HorizontalScrollBarVisibility="Disabled" Padding="5">
                        <ItemsControl ItemsSource="{Binding FirstRecord.Fields}" ItemTemplateSelector="{StaticResource FormView_TypeSelector}"/>
                    </ScrollViewer>
            </Grid>
        </telerik:RadBusyIndicator>

You're getting the current dispatcher from the non-UI thread, and trying to use that.

While you could get and store the current dispatcher from the UI thread, and then use that dispatcher later, what you should really do is just let the Background Worker handle marshaling to the UI thread for you, as you showed how to do in your working example, rather than trying to manually marshal to the 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