How do you work with gui from Async flow?



  • How do you work with gui from Async? Like, there's progressbar and there's button at the event. Async onclick the next code Await Task.Run((){progressbar.value = 77}) And he's, of course, flying out, so what am I gonna do?



  • How to use https://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext(v=vs.110).aspx ♪ Example:

    private async void ChangeProgressBar()
        {
            var uiSync = SynchronizationContext.Current;
            await Task.Run(() =>
            {
                uiSync.Send(state =>
                {
                    progressbar.value = 77
                }, null);
            });
        }
    

    Also, https://msdn.microsoft.com/en-us/library/hh193692%28v=vs.110%29.aspx ♪ Example:

        private async void ChangeProgressBar()
        {
            IProgress<int> progress = new Progress<int>(value => { progressBar.Value = value; });
    
        await Task.Run(async () =&gt;
        {
            for (int i = 0; i &lt; 100; i++)
            {
                progress.Report(i);
                await Task.Delay(20);
            }
        });
    }
    


    Another option is use https://msdn.microsoft.com/en-us/library/ms591593(v=vs.110).aspx ♪ Example:

    private async void ChangeProgressBar()
    {
    await Task.Run(() =>
    {
    progressBar.Dispatcher.Invoke(() => progressBar.Value = 77, DispatcherPriority.Background);
    });
    }




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2