Versuchen zu verstehen, wann ich ConfigureAwait() verwenden sollte. Accordin zum Buch:Grundlegendes ConfigureAwait
When an async method resumes after an await, by default it will resume executing within the same context. This can cause performance problems if that context was a UI context and a large number of async methods are resuming on the UI context.
Solution
To avoid resuming on a context, await the result of ConfigureAwait and pass false
for its continueOnCapturedContext parameter:
async Task ResumeWithoutContextAsync()
{
await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(false);
// This method discards its context when it resumes.
}
Was Kontext ist und wie ConfigureAwait zu sehen() ändert die Dinge in Beispielanwendung:
static async Task ResumeWithoutContextAsync()
{
await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(true);
Console.WriteLine("ManagedThreadId {0}", Thread.CurrentThread.ManagedThreadId);
// This method discards its context when it resumes.
}
static void Main(string[] args)
{
ResumeWithoutContextAsync();
Console.ReadLine();
}
Ich dachte, dass Kontext Thema ist, aber es ist nicht.
Es gibt einen Begriff namens "Blockierung". Einige Methoden kehren zurück, wenn die Arbeit synchron beendet wird (Blockierung) und andere sind asynchron (nicht blockierend) und kehren zurück, bevor alle Arbeiten abgeschlossen sind. Warten ist erforderlich, wenn eine Methode nicht blockiert ist und Sie warten müssen, bis alle Arbeiten abgeschlossen sind. – jdweng
https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html – peco