简体   繁体   中英

Async method continuation in different thread - means cooperative two-thread access to object variable?

When I write in async method:

public class myGameLoop
{
    protected class GameObject
    {
      ....
    }

    protected GameObject [] myGameObjects;

    public async Task myMethod()
    {
        myPrologue(); //runs on caller thread 1
        await SomeLongOperation().ConfigureAwait(false); //runs on thread 2
        myContinuation(); //maybe on thread 2 or another one from pool
    }
}

there is a possibility that myContinuation() will be executed not in the same thread than myPrologue(). Imagine that caller thread is a draw thread of a game. Then if myPrologue() changes non-atomic objects from myGameObjects array and myContinuation() works with them as well, we have unsynchronized access from 2 threads to object/array which can corrupt them.

Is it true or async/await has some synchronization stuff for such cases under the hood? Or I should avoid using ConfigureAwait(false)? (I'm not sure how much threads can have Monogame draw thread synchronization context, so I set ConfigureAwait to false to prevent accidental deadlocks).

(I'm not sure how much threads can have Monogame draw thread synchronization context, so I set ConfigureAwait to false to prevent accidental deadlocks).

I think this is the misunderstanding here. If the draw thread has its own synchronization context that is specifically for that thread, then if you use a plain await , it would resume on that draw thread. And it seems to me that's what you want .

The reason for ConfigureAwait(false) is not to "prevent accidental deadlocks". It's just to notify the await that you don't care what context you need to resume on. So if you do care what context you resume on, then of course you shouldn't use ConfigureAwait(false) .

More info in my async intro blog post.

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