简体   繁体   English

异步方法在不同线程中的延续-意味着对对象变量的协作式双线程访问?

[英]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(). 有可能在与myPrologue()不在同一线程中执行myContinuation()。 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. 然后,如果myPrologue()更改了myGameObjects数组中的非原子对象,并且myContinuation()也可以使用它们,则我们无法从2个线程对对象/数组进行非同步访问,这可能会破坏它们。

Is it true or async/await has some synchronization stuff for such cases under the hood? 是真的还是async / await在这种情况下有一些同步的东西? Or I should avoid using ConfigureAwait(false)? 还是我应该避免使用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). (我不确定Monogame绘制线程同步上下文可以包含多少个线程,因此我将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). (我不确定Monogame绘制线程同步上下文可以包含多少个线程,因此我将ConfigureAwait设置为false以防止意外死锁)。

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. 如果绘图线程具有自己的专用于该线程的同步上下文,则如果使用普通的await ,它将在该绘图线程上继续。 And it seems to me that's what you want . 在我看来,这就是您想要的

The reason for ConfigureAwait(false) is not to "prevent accidental deadlocks". ConfigureAwait(false)的原因不是为了“防止意外死锁”。 It's just to notify the await that you don't care what context you need to resume on. 只是通知正在await您,您不在乎需要恢复的上下文。 So if you do care what context you resume on, then of course you shouldn't use ConfigureAwait(false) . 因此,如果您确实在乎要恢复的上下文,那么您当然不应该使用ConfigureAwait(false)

More info in my async intro blog post. 有关更多信息,请参见我的async介绍博客文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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