Turn event into a async call

后端 未结 1 1608
春和景丽
春和景丽 2020-12-15 11:31

I\'m wrapping a library for my own use. To get a certain property I need to wait for an event. I\'m trying to wrap that into an async call.

Basically, I want to turn

1条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-15 12:13

    Thats where TaskCompletionSource comes into play. There is little room for the new async keyword here. Example:

    Task GetBarAsync()
    {
        TaskCompletionSource resultCompletionSource = new TaskCompletionSource();
    
        foo = new Foo();
        foo.Initialized += OnFooInit;
        foo.Initialized += delegate
        {
            resultCompletionSource.SetResult(foo.Bar);
        };
        foo.Start();
    
        return resultCompletionSource.Task;
    }
    

    Sample use (with fancy async)

    async void PrintBar()
    {
        // we can use await here since bar returns a Task of string
        string bar = await GetBarAsync();
    
        Console.WriteLine(bar);
    }
    

    0 讨论(0)
提交回复
热议问题