4

我知道从另一个线程更新 UI 线程的技术。

所以我有这两种方法/技术,我应该使用哪一种?

使用任务:

var uiTask = Task.Factory.StartNew(() => {
  // change something on ui thread
  var action = theActionOnUiThread;
  if (action != null) {
    action();
  }
}, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());

使用调度程序:

Dispatcher.CurrentDispatcher.BeginInvoke(
  new Action(() => {
    // change something on ui thread
    var action = theActionOnUiThread;
    if (action != null) {
      action();
    }
  }));
4

2 回答 2

2

From a technical point of view I doubt there is a 'best' here. however I'd go with the dispatcher approach:

  • it makes your intent more clear, namely that you want to get something done on the main ui thread
  • you don't need to boter with all the task factory options
  • Dispatcher makes it easier to hide everything behind an interface (1) allowing easy dependency injection and unit testing

(1) see here for example

于 2012-12-15T21:12:27.060 回答
1

TaskScheduler.FromCurrentSynchronizationContext()不保证TaskScheduler为 UI 线程返回一个。

实际上它有时会返回null,尽管这些情况很少见,并且通常涉及在本机应用程序(例如 WIX 引导程序)中启动您自己的调度程序。

所以我会说使用调度程序版本更安全。

于 2012-12-17T09:03:08.053 回答