2016-06-28 38 views
0

我有以下异步方法是应该得到我需要根据传递到方法的列表中的所有字符串:如何使用ContinueWith这个例子

public async Task<List<string>> GetStrings(List selections) 
{ 
    List<string> myList = new List<string>(); 
    TaskCompletionSource<List<string>> someStrings = new TaskCompletionSource<List<string>>(); 

    // Register/deregister event that is fired on each selection. 
    // Once this event is received, I get its arguments from which I 
    // get string and add it to my list of strings. 
    // Once the list count matches number of selections passed into the method, 
    // TaskCompletionSource result is set. 
    EventHandler<IDataNotification> onCallThatFiresCompleted = null; 
    onCallThatFiresCompleted = (sender, e) => 
    { 
     var myString = e.getString(); 
     myList.Add(myString); 
     if (myList.Count == selections.Count) 
     { 
      MyObserver.DataNotification -= onCallThatFiresCompleted; 
      someStrings.TrySetResult(myList); 
     } 
    }; 
    MyObserver.DataNotification += onCallThatFiresCompleted; 


    foreach (var sel in selections) 
    { 
     // This call fires onCallThatFiresCompleted event that when received 
     // will conteain string I need in its arguments. 
     CallThatFires_MyEvent(); 
    } 

    return await someStrings.Task; //await for the task 
} 

如何将这种方法应用任务的调用者。 ContinueWith()在任务完成后处理返回的列表?我想要做这样的事情:

foreach(var s in returnedStringList) 
{ 
    // do something with the string s 
} 
+2

为什么在调用者可以执行时使用'Task.ContinueWith()'var returnedStringList = await GetStrings(someList)'?另外,你在做什么问题时使用'ContinueWith('显示你的尝试代码。 –

+0

@ScottChamberlain你是对的,我可以使用await。但是我想了解如何使用ContinueWith和从我阅读的内容,它允许用户在可用的时候继续返回数据,但是我无法弄清楚如何编写在这种情况下工作的ContinueWith(或者其他任何我以前从未使用过的)。控制取消和故障,ContinueWith提供。非常感谢。 – pixel

+0

@ScottChamberlain如果调用者是'Main';) –

回答

3

如何使用ContinueWith这个例子

你不知道。您可以使用await

var returnedStringList = await GetStrings(..); 
foreach(var s in returnedStringList) 
{ 
    // do something with the string s 
} 

当我描述我的博客上,await is superior in every way to ContinueWith异步代码。

+0

谢谢,这工作 – pixel