简体   繁体   中英

Awaiting 2 tasks, one is awaiting the other

Is it thread safe to await 2 tasks (one of the tasks is awaiting the other)?

public async Task<string> Operation1(){}

public async Task<string> Operation2( Task waitMe)
{
    if(DoSomethingSuccess())
        return "EarlySuccess";

    var result = await waitMe;
    return SomeSideEffectThat( result); // I read result
}

void async Task<string> MyMainFunction(){

    Task<string> t1 = Operation1();
    Task<string> t2 = Operation2( t1);

    var result = await Task.WaitAny( new Task<string> { t1, t2});
    if(results.Status == TaskStatus.RanToCompletion)
        return result;

    return "ExceptionOccurred";


}

I'm interested in having the first result from one of the tasks, and eventually the second task to perform side effects. Assume side effects are already thread safe, I'm interested in race conditions over "t2" "t1" and "result" storing.

I need both 2 the operations to run in parallel, that's why I don't continue T1 with T2, it is just that T2 needs T1 to perform some additional operations

why dont you just use ContinueWith

  Task.Factory.StartNew(() => negate(5))
         //you can go with another task here  
        .ContinueWith(antecendent => negate(antecendent.Result))        ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM