Wie zu verwenden Aufgabe.WhenAll richtig

Folgenden diese Frage (und seine Antwort), das ich verwenden möchte TaskCompletionSource und Task.WhenAll zu warten, bis Wann jede Aufgabe gibt True zurück Erstens. Also schrieb ich dies :

TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
Task<bool> t0 = Task.Factory.StartNew<bool>(() => Find(paramA, paramB);
Task<bool> t1 = Task.Factory.StartNew<bool>(() => Find(paramC, paramD);
Task<bool> t2 = Task.Factory.StartNew<bool>(() => Find(paramE, paramF);
Task<bool> t3 = Task.Factory.StartNew<bool>(() => Find(paramG, paramH);

t0.ContinueWith(_ =>
{
    if (t0.Result)
        tcs.TrySetResult(t0.Result);
});

t1.ContinueWith(_ =>
{
    if (t1.Result)
        tcs.TrySetResult(t1.Result);
});

t2.ContinueWith(_ =>
{
    if (t2.Result)
        tcs.TrySetResult(t2.Result);
});

t3.ContinueWith(_ =>
{
    if (t3.Result)
        tcs.TrySetResult(t3.Result);
});

t4.ContinueWith(_ =>
{
    if (t4.Result)
        tcs.TrySetResult(t4.Result);
});

tcs.Task.Wait();
return tcs.Task.Result;

es funktioniert, wenn jede Aufgabe gibt true aber, wie bemerkt, in der Antwort zuvor :

Das knifflige bit ist zu bemerken, wenn alle Aufgaben falsch zurückgegeben... in
.NET 4.5 das wäre relativ einfach, durch die Schaffung einer anderen Aufgabe über
Aufgabe.WhenAll

So, ich habe versucht, zu spielen mit Task.WhenAll aber ich will nicht, um es richtig zu verwenden...

Ich habe versucht, so etwas wie, dass :

tcs.Task.Wait(); //stays block here when all tasks return false
Task tr = Task.WhenAll(new Task[] { t0, t1, t2, t3, t4 });

if (tr.IsCompleted)
   return false;
else
return tcs.Task.Result;

Danke für Eure Hilfe

  • und die Frage ist? 🙂
  • Wie zu verwenden Aufgabe.WhenAll um ein Ergebnis zu erhalten, auch wenn alle tasks return false ?
InformationsquelleAutor Florian | 2012-08-07
Schreibe einen Kommentar