Are you there, asynchronously written value?

后端 未结 2 1195
轻奢々
轻奢々 2021-01-18 12:24

The last couple of days I\'ve been reading about async/await. Yesterday I found this video on Channel 9 what made wonder about some things. Please consider the slide below.<

2条回答
  •  有刺的猬
    2021-01-18 13:08

    But what happens to the variable? It could be written by a different thread than it is read.

    If m_GetResponse is a private field, and this class gets invoked multiple times by different threads, then yes, it is possible for the value to be "dirty" once someone else tries to read it. In order to make it thread-safe, you could lock around it. It seems that the authors intention was to invoke this from the UI thread only, hence him making SendData a private method. In that case, it is safe for m_GetResponse to be a private field, as the continuation of the async method which is responsible for the variable assignment will happen inside the UI message loop.

    Could it still be null when we print it?

    It could be null if somewhere else in the code, someone sets that variable to null, as it's a class level variable. If you're talking about "could it be that we try to print m_GetResponse before await finishes the state-machine execution, then no. Again, i'm not sure the authors intentions were made around concurrent execution, but rather to show you async-await features.

    or perhaps something else?

    In order to make it thread safe, you can simply remove the global variable, and return a local variable instead. SendData shouldn't be async void anyway, as it isn't used for event handler delegate assignment like Button1_Click.

    You could do it better like this (i'll use HttpClient for simplicity):

    public async Task SendDataAsync(string url)
    {
        var httpClient = new HttpClient();
        var response = await httpClient.GetAsync();
        return response.Content.ReadAsStringAsync();
    }
    

    Note you should remember that async-await isn't meant to address parallelism, it's more about concurrency and easing the use of naturally async IO operations.

提交回复
热议问题