如何使用任务时ContinueWith从previous任务结果的另一个功能?任务、如何使用、功能、结果

2023-09-04 01:45:18 作者:跑到坟场去吓鬼

我有应该得到一些少量的数据为我的WCF连接器,通常它需要长达20秒,以得到这个数据的每个项(这是细)。我想用任务来获得我的数据,然后用值从这个任务中添加的WinForm控件。

I have WCF connector that should get some small amount of data for me, usually it takes up to 20 seconds to get this data for each item ( which is fine ). I want to use Task to get data for me and then add WinForm controls with value from this Tasks.

我创建的对象的列表,其中将包括此数据。

I've created list of objects which will consist this data.

用于第一项任务作为其中一个更新列表,我想任务就是马上后,第一项任务是为了创建控件。

Used first Task as the one which updates the list and i want Task that is right away after first Task is done to create controls.

这是在code到目前为止:

This is the code so far:

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从第一种方法传递值第二。

I don't know if i'm going right way and how to use ContinueWith to pass value from first method to second.

推荐答案

在低于T的例子引用previous任务,使用结果属性从它那里得到的返回值。

In the example below t references the previous task, use the Result property to get the return value from it.

Task task = Task.Factory.StartNew(() =>
{
   // Background work
}).ContinueWith((t) => 
{
   var ipVersionCounters = t.Result;
});

更新

如果您希望continuewith对UI线程使用EXECUTE(如果你开始在UI线程)

If you want the continuewith to execute on the UI thread use (If you are starting on the UI thread) ...

Task.Factory.StartNew(() =>
            {
                // Background work
            }).ContinueWith((t) => {
                // Update UI thread

            }, TaskScheduler.FromCurrentSynchronizationContext());

(其从this回答获取更多信息)

(which was taken from this answer for more info)