簡體   English   中英

有什么理由立即使用 await 和 async 嗎?

[英]Is there any reason to use await and async right away?

我在網上找到了這段代碼。

    If request.Content IsNot Nothing Then
        ' Hash content to ensure message integrity
        Using md5__1 = MD5.Create()
            requestContentBase64String = Convert.ToBase64String(md5__1.ComputeHash(Await request.Content.ReadAsByteArrayAsync()))
        End Using
    End If

做一些異步事情的全部意義在於,在等待異步事情完成的同時,可以先完成其他事情。

所以

dim task = somethingasync()
doSomething
await task

會有意義

但是await somethingasync對我來說沒有任何意義。 重點是什么? 反正你什么都沒做。 無論如何,您都要等到某事異步完成。

事實上,即使

dim task = somethingasync()
doSomething
await task

包含 await 運算符的東西不應該在主 UI 線程上,對嗎? 那是因為我們不希望用戶等待。

這是事情。 如果整個事情發生在非主 UI 線程中,那么讓整個事情等待結果有什么意義?

為什么不使用同步版本?

檢查您的功能:

您可以在 async 函數中進行異步操作:

//Wrong
void AsyncCallFunc()
    {
        AsyncFunc();
        //doSomething
    }

//Correct
async void TrueAsyncCallFunc()
    {
        await AsyncFunc();
        //doSomething
    }

此外,如果你用 try-catch 包圍它,你可以選擇在 finally 中添加你的最終操作。 它會在你所有的 try 操作之后立即運行:

async void TrueAsyncCallFunc()
    {
        try{
            await AsyncFunc();
            //doSomething
        }
        catch(Exception){
            throw;
        }
        finally{
            //do last operation
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM