Turn event into a async call

后端 未结 1 1605
春和景丽
春和景丽 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<string> GetBarAsync()
    {
        TaskCompletionSource<string> resultCompletionSource = new TaskCompletionSource<string>();
    
        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)
提交回复
热议问题