Task.Run and UI Progress Updates

前端 未结 3 1217
耶瑟儿~
耶瑟儿~ 2020-12-01 14:12

This code snippet is from Stephen Cleary\'s blog and gives an example of how to report progress when using Task.Run. I would like to know why there are no cross thread issue

3条回答
  •  情深已故
    2020-12-01 14:33

    The Progress constructor captures the current SynchronizationContext object.

    The SynchronizationContext class is a facility that abstracts the particulars of the involved threading model. That is, in Windows Forms it will use Control.Invoke, in WPF it will use Dispatcher.Invoke, etc.

    When the progress.Report object is called, the Progress object itself knows that it should run its delegate using the captured SynchronizationContext.

    In other terms, it works because Progress has been designed to handle that without the developer having to explicitly say it.

提交回复
热议问题