What's the method signature for passing an async delegate?

后端 未结 3 1558
一整个雨季
一整个雨季 2020-12-08 13:11

I\'ve recently moved back to C# from being in Objective-C land, and the async/await keywords in C# 5 look cool. But I\'m still trying to get a handle on the proper syntax.

3条回答
  •  执念已碎
    2020-12-08 13:21

    If I have a task that I want to be passed but not executed, I can wrap the Task in a Func<>, then call that Func<> to create that task. The await can be used in the normal way.

    public class Example {
        public Example(Func toBeExecutedInTheFuture)
        {
            FutureTask = toBeExecutedInTheFuture;
        }
    
        public async void ExecuteTaskExample()
        {
            await FutureTask();
    
            // or alternatively
    
            var myTask = FutureTask();
            // do work
            await myTask;
        }
    }
    

提交回复
热议问题