0

SendOrPostCallback Represents a method to be called when a message is to be dispatched to a synchronization context. In first case SendOrPostCallback points on async method that i guess should be executed synchronously. What will happen if Delegate will point on async delegate? How behaviour should change?

Before changes:

public class ViewModel
{
    public ViewModel()
    {
        SynchronizationContext.Current.Post(new SendOrPostCallback(SomeMethods), null);
    }

    private async void SomeMethods(object obj)
    {
        await Foo(obj);
    }

    private async Task Foo(object obj)
    {
        bool Canceled = false;
        while (!Canceled)
        {
            await Task.Delay(3000);
            //...
        }
    }
}

After changes:

public class ViewModelImproved
{
    public ViewModelImproved()
    {
        SynchronizationContext.Current.Post(new SendOrPostCallback(async (obj) => { await SomeMethods(obj); }), null);
    }

    private async Task SomeMethods(object obj)
    {
        await Foo(obj);
    }

    private async Task Foo(object obj)
    {
        bool Canceled = false;
        while (!Canceled)
        {
            await Task.Delay(3000);
        }
        //...
    }
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
A191919
  • 3,422
  • 7
  • 49
  • 93
  • `async` is not a part of a method signature. `SendOrPostCallback` is a `delegate void`, so the async method you pass will be called in the [fire-and-forget mode](https://stackoverflow.com/q/18502745/11683). – GSerg Jul 25 '19 at 10:41
  • @GSerg,if i understand correct in both cases will be the same execution behaviour? Fire and forget in first case and in second also? – A191919 Jul 25 '19 at 11:03
  • Yes, because the outer method is still `void`. – GSerg Jul 25 '19 at 11:40

1 Answers1

2

There's no substantial difference. In the first code, there's an async void, and in the second code, there's an async void. In the second code, the async void is hidden within a lambda expression.

Generally, you should avoid async void. In this particular case, it may be OK, since you're dealing with a UI context.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810