我该如何从任务UI线程更新?

Nig*_*ker 8 .net c# wpf task task-parallel-library

我有一项任务,执行一些繁重的工作.我需要把结果归结为LogContent

Task<Tuple<SupportedComunicationFormats, List<Tuple<TimeSpan, string>>>>.Factory
    .StartNew(() => DoWork(dlg.FileName))
    .ContinueWith(obj => LogContent = obj.Result);
Run Code Online (Sandbox Code Playgroud)

这是属性:

public Tuple<SupportedComunicationFormats, List<Tuple<TimeSpan, string>>> LogContent
{
    get { return _logContent; }
    private set
    {
        _logContent = value;
        if (_logContent != null)
        {
            string entry = string.Format("Recognized {0} log file",_logContent.Item1);
            _traceEntryQueue.AddEntry(Origin.Internal, entry);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是_traceEntryQueue绑定到UI的数据,因为我会在这样的代码上有异常.

所以,我的问题是如何让它正常工作?

Ser*_*nov 16

这是一篇好文章:并行编程:任务调度程序和同步上下文.

看看Task.ContinueWith()方法.

例:

var context = TaskScheduler.FromCurrentSynchronizationContext();
var task = new Task<TResult>(() =>
    {
        TResult r = ...;
        return r;
    });

task.ContinueWith(t =>
    {
        // Update UI (and UI-related data) here: success status.
        // t.Result contains the result.
    },
    CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, context);

task.ContinueWith(t =>
    {
        AggregateException aggregateException = t.Exception;
        aggregateException.Handle(exception => true);
        // Update UI (and UI-related data) here: failed status.
        // t.Exception contains the occured exception.
    },
    CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, context);

task.Start();
Run Code Online (Sandbox Code Playgroud)

由于.NET 4.5支持async/ await关键字(另请参见Task.Run与Task.Factory.StartNew):

try
{
    var result = await Task.Run(() => GetResult());
    // Update UI: success.
    // Use the result.
}
catch (Exception ex)
{
    // Update UI: fail.
    // Use the exception.
}
Run Code Online (Sandbox Code Playgroud)


bob*_*lez 5

您需要在UI线程上运行ContinueWith -task.这可以使用UI线程的TaskScheduler和ContinueWith -method重载版本来完成,即.

TaskScheduler scheduler = TaskScheduler.Current;
...ContinueWith(obj => LogContent = obj.Result), CancellationToken.None, TaskContinuationOptions.None, scheduler)
Run Code Online (Sandbox Code Playgroud)