[英]How to wait for Tasks to finish with Task.WhenAll ?
This all works so far but there are 2 things that bother me and I think I am using the wrong way 到目前为止,所有方法都有效,但是有两件事困扰着我,我认为我使用了错误的方式
Problem #1 - I only want to return a string but I seem forced to return a string ARRAY. 问题#1-我只想返回一个字符串,但是我似乎被迫返回一个字符串ARRAY。 How can I just make this return a string ? 我怎样才能使它返回一个字符串?
Task<string> taskVelocifyData = GetVelocifyData();
string[] userEmail = await Task.WhenAll(taskVelocifyData);
Problem #2 - Not sure if this is a problem but is this the optimal to wait for async tasks to complete before going to the next async task ? 问题2-不确定是否存在问题,但这是否是等待下一个异步任务完成之前等待异步任务的最佳选择?
private async void DispatcherTimer_Tick(object sender, object e)
{
List<string>[] photos = new List<string>[10];
try
{
//Use Velocify API to get most recent lead
Task<string> taskVelocifyData = GetVelocifyData();
string[] userEmail = await Task.WhenAll(taskVelocifyData);
//Ignore recent lead if it has not changed
if (lsi.VelocifyLeadTitle != previousVelocifyLeadTitle)
{
//If there is an email, use FullContact API to get photos
if (userEmail[0] != "")
{
var taskFullContactData = GetFullContactData(userEmail[0]);
photos = await Task.WhenAll(taskFullContactData);
if (photos.Count() != 0)
{
var taskFaceData = GetFaceData(photos);
}
}
else
{
lsi.FullContactPictures = new ObservableCollection<string>();
}
// DEBUG
// dispatcherTimer.Stop();
LeadSpeakerItems.Add(lsi);
SpeakData(leadSpeakerItems.Last().VelocifyLeadTitle);
}
previousVelocifyLeadTitle = lsi.VelocifyLeadTitle;
}
catch (Exception ex)
{
}
You have a single Task
, so you can await
it directly. 您只有一个Task
,因此可以直接await
它。 You don't need Task.WhenAll
. 您不需要Task.WhenAll
。
string userEmail = await GetVelocifyData();
The Task.WhenAll
method Task.WhenAll
方法
Creates a task that will complete when all of the System.Threading.Tasks.Task objects in an enumerable collection have completed. 创建一个将在可枚举集合中的所有System.Threading.Tasks.Task对象都完成时完成的任务。
When completed, the task will return an array with results of all tasks passed to Task.WhenAll
. 完成后,任务将返回一个数组,其中包含所有传递给Task.WhenAll
任务的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.