我应该如何从Task更新UI线程? [英] How should I update from Task the UI Thread?
本文介绍了我应该如何从Task更新UI线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的任务是执行一些繁重的工作。
我需要将其结果路径为 LogContent
I have a task that performing some heavy work.
I need to path it's result to 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
是绑定到UI的数据,原因是我在这样的代码上会有异常。
Problem is that _traceEntryQueue
is data bound to UI, and of cause I will have exception on code like this.
所以,我的问题是使其正常工作?
So, my question is how to make it work correctly?
推荐答案
您需要在UI线程上运行ContinueWith -task。可以使用UI线程的TaskScheduler和 ContinueWith的重载版本来完成-方法,即。
You need to run the ContinueWith -task on the UI thread. This can be accomplished using the TaskScheduler of the UI thread with the overloaded version of the ContinueWith -method, ie.
TaskScheduler scheduler = TaskScheduler.Current;
...ContinueWith(obj => LogContent = obj.Result), CancellationToken.None, TaskContinuationOptions.None, scheduler)
这篇关于我应该如何从Task更新UI线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文