I can solve this in .Net 4.5 but I must solve it in .Net 4.0, and so far i have not been successful.
I have not been able to get my replies into a Task<List<MyDataObject>>
. The code below can create List<MyDataObject>
.
public Task<List<MyDataObject>> Foo()
{
IEnumerable<string> names = GetList();
var tasks = new List<Task>();
foreach (var name in names)
{ tasks.Add(Task<MyDataObject>.Factory.StartNew(
() =>
{
var reply = new MyDataObject();
var workerObject = new WorkerObject();
workerObject.Foo2();
reply.Success = true;
return reply;
}));
}
Task.WaitAll(tasks.ToArray());
var replyList = new List<MyDataObject>();
for (int i = 0; i < tasks.Count(); i++)
{ replyList.Add(((Task<MyDataObject>)tasks[i]).Result);
}
return replyList;
}
WhenAll()
is 4.5 only
await
is 4.5 only
so i cannot accept those
I agree that this doesnt compile. What I showed was i can iterate through the results. However I do not know how to go from
List<MyDataObject>()
to
Task<List<MyDataObject>>
Thank you for the replies. I am going to accept Yuval Itzchakov's answer because it solves my problem in a simple manner. I am limited to no new assemblies for this use case. I would have selected 280Z28's second option had I had another method that required this functionality.
>` yet you return a `List`. Without knowing about `Task`s, this looks like a compile-time issue to me.
– Jashaszun Aug 04 '14 at 17:46