Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

c# - To run or not run ConfigureAwait(false) with both services and activities with Xamarin Android ver 8, .net Standard

I came across articles below regarding when and where to use ConfigureAwait(false), but cannot get an answer.

You Don’t Need ConfigureAwait(false), But Still Use It in Libraries, and UI apps. (e.g. Xamarin, WinForms etc)

https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html

This link says opposite answer

Best practice to call ConfigureAwait for all server-side code

When correctly use Task.Run and when just async-await

My questions:

Scenario 1: The code below is running as background service.

My question: Is ConfigureAwait(false) required for whenever await is used like both A and B below:

    [Service(Name = "com.MainApplicationService", Label = "Main Application Service", Exported = false)]
    public class MainApplicationService : Android.App.Service
    {

        public override IBinder OnBind(Intent intent)
        {
            return null;
        }

        [return: GeneratedEnum]
        public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
        {
            await InitAsync().ConfigureAwait(false);   //line A

            Task.Run(async () => await InitAsync().ConfigureAwait(false));   //line B

            return StartCommandResult.Sticky;
        }
    }

Scenario 2: The code below is running as UI thread as opposed to background service

Same question: Is ConfigureAwait(false) required for whenever await is used like both C and D below:

public class StartupActivity : Android.App.Activity
{
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        await InitAsync().ConfigureAwait(false);  //line C

        Task.Run(async () => await InitAsync().ConfigureAwait(false));  //line D

        Finish();
    }
}

Xamarin Android ver 8, I think it is .net standard.

https://github.com/davidfowl/AspNetCoreDiagnosticScenarios/blob/master/AsyncGuidance.md

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Perhaps an unpopular opinion, but these days I don't use ConfigureAwait(false) even in libraries, see:

"Revisiting Task.ConfigureAwait(continueOnCapturedContext: false)"

IMO, if the code that consumes a Task-based API is concerned about the current synchronization context and how it might affect that API's behavior (deadlocks, redundant context switches, etc.), it can explicitly wrap the API invocation with Task.Run or use something like TaskExt.WithNoContext from the above link:

await Task.Run(() => InitAsync());
// or
await TaskExt.WithNoContext(() => InitAsync());

In most cases though, especially for UI apps (where there's a synchronization context, but threading scalability is not an issue), it's OK to leave it as is, without Task.Run or ConfigureAwait:

await InitAsync();

This would give you a chance to discover and investigate potential deadlocks, before trying to mitigate them with ConfigureAwait(false) or Task.Run.

So, it is not always a bad idea to continue on the same synchronization context, especially inside async void methods where unhandled exceptions are posted to the current synchronization context, see TAP global exception handler.


Updated to answer the questions in the comments:

What is the difference between await Task.Run(() => InitAsync()); and Task.Run(async () => await InitAsync()); and await Task.Run(async () => await InitAsync());

In this case (a simple async lambda to Task.Run) the difference would be just an extra overhead of async/await compiler-generated state machine, which you don't need. The task, returned by InitAsync, will get unwrapped by Task.Run automatically, either way. For more general cases, see "Any difference between "await Task.Run(); return;" and "return Task.Run()"?".

I'd use an async lambda here only if I needed to do something else after the completion of InitAsync, while still not having to worry about synchronization context, e.g.:

await Task.Run(async() => {
    await InitAsync();
    // we're on a pool thread without SynchronizationContext
    log("initialized");
});

Double check: use discard like this _ = WorkAsync(); to suppress warning, but it doesn't catch exception. To handle exception, I need to define an extension method like Forget. on Fire and Forget approach

Yes, that'd be my choice for fire-and-forget. However, I don't think your InitAsync is a true fire-and-forget in your case. Perhaps, it'd be better to keep track of it in the class instance: _task = InitAsync() and observe _task later.

Or, better yet, you could use an async void helper method inside OnCreate to observe the result/exceptions of InvokeAsync:

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);

    async void function invokeInitAsync()
    {
        try 
        {
            await InitAsync();
            Finish();
        }
        catch(Exception e) {
            // handle the failure to initialize
            await promptAndExitUponErrorAsync(e);
        }
    }

    invokeInitAsync();
}

It might be possible to make OnCreate itself async void, but then exceptions (if any) from base.OnCreate() wouldn't be getting synchronously propagated to the caller of your override, which may have other side effects. Thus, I'd use a helper async void method, which can be also local as above.

Finally, consider embracing asynchrony in your ViewModel layer, and then you woudn't have to worry about it in places like OnCreate. For more details, see: "How to Unit test ViewModel with async initialization in WPF".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...