FetchDataAsync that returns a string after a delaycontinueOnCapturedContext to control ConfigureAwaitConfigureAwait(continueOnCapturedContext) when awaiting the delayFetchDataAsync that returns a string after a delaycontinueOnCapturedContext to control ConfigureAwaitConfigureAwait(continueOnCapturedContext) when awaiting the delayFetchDataAsyncFetchDataAsync that waits 1000 milliseconds using Task.Delay(1000) and then returns the string "Data fetched".Use async Task<string> for the method signature and await Task.Delay(1000) inside the method.
continueOnCapturedContext boolean variableProgram class, add a public static boolean variable called continueOnCapturedContext and set it to false.Declare continueOnCapturedContext as a public static bool and set it to false.
ConfigureAwait with continueOnCapturedContextFetchDataAsync method to use ConfigureAwait(continueOnCapturedContext) after Task.Delay(1000).Use ConfigureAwait(continueOnCapturedContext) right after Task.Delay(1000).
ConfigureAwait effectMain method that prints "Starting fetch", calls FetchDataAsync() with await, prints the returned data, and then prints "Fetch complete". Use continueOnCapturedContext = false before calling FetchDataAsync.Use Console.WriteLine to print messages before and after awaiting FetchDataAsync().
What does ConfigureAwait(false) do in an async method?
ConfigureAwait(false) means the continuation after await does not have to run on the original context (like UI thread).Which of the following is the correct syntax to avoid resuming on the original context after an await?
await SomeAsyncMethod()...ConfigureAwait takes a boolean parameter: true or false.false tells the continuation not to resume on the original context.Consider the following code snippet:
async Task Example()
{
Console.WriteLine($"Start on thread {Thread.CurrentThread.ManagedThreadId}");
await Task.Delay(100).ConfigureAwait(false);
Console.WriteLine($"After await on thread {Thread.CurrentThread.ManagedThreadId}");
}What is the likely output behavior regarding thread IDs?
ConfigureAwait(false) means the continuation after await can run on any thread, not necessarily the original one.Identify the problem in this code snippet:
public async Task LoadDataAsync()
{
var data = await GetDataAsync().ConfigureAwait(true);
UpdateUI(data);
}
void UpdateUI(string data)
{
// Update UI elements here
}What issue might occur and how to fix it?
You have a library method async Task<string> FetchDataAsync() that uses ConfigureAwait(false). You want to call it from a UI app and update UI controls after awaiting. How should you write your calling code to safely update the UI?
ConfigureAwait(false) internally, avoiding context capture inside library method.await FetchDataAsync() defaults to ConfigureAwait(true), resuming continuation on original UI context.Pass the test and this pattern moves unknown