gpt4 book ai didi

c# - 我应该如何从 Task 更新 UI 线程?

转载 作者:太空狗 更新时间:2023-10-29 18:06:45 24 4
gpt4 key购买 nike

我有一项任务是执行一些繁重的工作。我需要将其结果指向 LogContent

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

这是属性:

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);
}
}
}

问题是 _traceEntryQueue 是绑定(bind)到 UI 的数据,因此我对这样的代码会有异常。

那么,我的问题是如何让它正常工作?

最佳答案

这是一篇好文章:Parallel Programming: Task Schedulers and Synchronization Context .

看看Task.ContinueWith() method .

例子:

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();

由于 .NET 4.5 支持 async/await 关键字(另见 Task.Run vs 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.
}

关于c# - 我应该如何从 Task 更新 UI 线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14620060/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com