且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

投放任务< T>到Task< object>在没有T的C#中

更新时间:2022-03-11 07:44:50

您可以分两步完成-使用基类await进行任务,然后使用反射或dynamic收获结果:

You can do it in two steps - await the task using the base class, then harvest the result using reflection or dynamic:

using(var context = new DbContext()) {
    // Get the task
    Task task = (Task)typeof(MyContextExtensions).GetMethod(methodName).Invoke(null, context);
    // Make sure it runs to completion
    await task.ConfigureAwait(false);
    // Harvest the result
    return (object)((dynamic)task).Result;
}

这是一个完整的运行示例,将通过反射调用Task的上述技术置于上下文中:

Here is a complete running example that puts in context the above technique of calling Task through reflection:

class MainClass {
    public static void Main(string[] args) {
        var t1 = Task.Run(async () => Console.WriteLine(await Bar("Foo1")));
        var t2 = Task.Run(async () => Console.WriteLine(await Bar("Foo2")));
        Task.WaitAll(t1, t2);
    }
    public static async Task<object> Bar(string name) {
        Task t = (Task)typeof(MainClass).GetMethod(name).Invoke(null, new object[] { "bar" });
        await t.ConfigureAwait(false);
        return (object)((dynamic)t).Result;
    }
    public static Task<string> Foo1(string s) {
        return Task.FromResult("hello");
    }
    public static Task<bool> Foo2(string s) {
        return Task.FromResult(true);
    }
}