Home > Back-end >  When adding an async delegate to an event, how to make the process continue after the event is done?
When adding an async delegate to an event, how to make the process continue after the event is done?

Time:08-24

I'm not sure if the title is clear. I mean that if I have code like this:

public class Test
{
    public event EventHandler? Started;
    public event EventHandler? Finished;

    public void DoWork()
    {
        Console.WriteLine("Start");
        Started?.Invoke(this, EventArgs.Empty);
        Console.WriteLine("End");
        Finished?.Invoke(this, EventArgs.Empty);
    }
}

public static class Program
{
    public static async Task Main(string[] args)
    {
        var test = new Test();
        //When adding an async delegate to an event, how to make it run synchronously?
        test.Started  = async delegate
        {
            Console.WriteLine("The started event began.");
            await Task.Delay(3000);
            // this string will not be printed
            Console.WriteLine("The started event ended.");
        };
        test.Finished  = (_, _) => { Console.WriteLine("Run finished event"); };
        test.DoWork();
    }
}

The Finished event will be raised before the Started runs finished.

Is there's any way to make the Started event be raised after Finished event is done?

Please help! Thanks!

CodePudding user response:

You make the delegate async and stop using EventHandler. Also DoWork needs to be async.

public class Test
{
    public event Func<object, Task>? Started;
    public event Func<object, Task>? Finished;

    public async Task DoWork()
    {
        Console.WriteLine("Start");
        if (Started is not null)
        {
            await Started.Invoke();
        }
        Console.WriteLine("End");
        if (Finished is not null)
        {
            await Finished.Invoke();
        }
    }
}

public static class Program
{
    public static async Task Main(string[] args)
    {
        var test = new Test();
        //When adding an async delegate to an event, how to make it run synchronously?
        test.Started  = async delegate
        {
            Console.WriteLine("The started event began.");
            await Task.Delay(3000);
            // this string will not be printed
            Console.WriteLine("The started event ended.");
        };
        test.Finished  = (_) => { Console.WriteLine("Run finished event"); return Task.CompletedTask; };
        await test.DoWork();
    }
}
  • Related