我有 WCF 连接器,它应该为我获取一些少量的数据,通常需要 20 秒才能获取每个项目的数据(这很好)。我想使用任务为我获取数据,然后添加具有此任务值的 WinForm 控件。
我已经创建了包含这些数据的对象列表。
使用第一个任务作为更新列表的任务,我希望第一个任务完成后立即执行任务来创建控件。
这是到目前为止的代码:
List<IpVersionCounter> ipVersionCounters = new List<IpVersionCounter>();
Task task = Task.Factory.StartNew(() =>
{
foreach (var sitein settings.Sites)
{
string ip = site.ip;
string version = "undefined";
using (WcfConnector wcfConnector =
WcfConnector.CreateConnectorWithoutException((ip)))
{
if (wcfConnector != null)
{
version= string.Format("{0} {1} {2}",
wcfConnector.VersionController.GetBranchName(),
wcfConnector.VersionController.GetBuildNumber(),
wcfConnector.VersionController.GetCurrentVersion());
}
}
counter++;
ipVersionCounters.Add(new IpVersionCounter
{
Ip = ip,
Version = Version,
Counter = counter
});
}
return ipVersionCounters;
}).ContinueWith();
AddProgressBar(ipVersionCounter);
我不知道我是否走对了路,也不知道如何使用ContinueWith将值从第一个方法传递到第二个方法。
在下面的例子中previousTask
引用前一个任务,使用 Result 属性从中获取返回值。
Task task = Task.Factory.StartNew(() =>
{
// Background work
return ipVersionCounters;
}).ContinueWith((previousTask) =>
{
var ipVersionCounters = previousTask.Result;
});
Update
如果您希望 continuewith 在 UI 线程上执行,请使用(如果您在 UI 线程上启动)...
Task.Factory.StartNew(() =>
{
// Background work
}).ContinueWith((previousTask) => {
// Update UI thread
}, TaskScheduler.FromCurrentSynchronizationContext());
(取自this https://stackoverflow.com/questions/7582853/what-wpf-threading-approach-should-i-go-with/7584422#7584422回答以获取更多信息)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)