简体   繁体   English

如何将任务转换为任务 <T> ?

[英]How to convert a Task into a Task<T>?

I'm sure this has been asked before but I can't seem to phrase the question right to get any answers that solve my question. 我敢肯定这已经被问过了,但是我似乎无法正确表达问题的意思,以获取解决我问题的任何答案。

I've got a base class that implements an interface with a Save method that returns a Task: 我有一个基类,该基类使用可返回Task的Save方法实现接口:

public interface ICanSave
{
    Task Save();
}

public class Base : ICanSave
{
    public Task Save()
    {
        return Task.CompletedTask;
    }
}

Of course the Save method will actually do something, like saving to a database, which is why it's a Task, so it can be awaited. 当然,Save方法实际上会执行某些操作,例如保存到数据库,这就是为什么它是Task的原因,因此可以等待它。 If I have a Foo class that inherits from the base class: 如果我有一个从基类继承的Foo类:

public class Foo : Base { }

Currently, you'd have to do the instantiation and save in two distinct steps: 当前,您必须执行实例化并保存两个不同的步骤:

var foo = new Foo();

await foo.Save();

However I'd like to be able to do the instantiation and the save as an expression and return a Task also. 但是,我希望能够将实例化和另存为表达式,并且还返回Task。 I've come up with this helper: 我想出了这个助手:

public static class Helper<T> where T : ICanSave
{
    public static Task<T> Save(T obj)
    {
        var source = new TaskCompletionSource<T>();

        ThreadPool.QueueUserWorkItem(_ =>
        {
            obj.Save();
            source.SetResult(obj);
        });

        return source.Task;
    }
}

Which could then be used to do: 然后可以用来执行以下操作:

var foo = await Helper<Foo>.Save(new Foo());

Which is more like the result I'm trying to achieve, but it seems pretty cumbersome, plus the helper seems to be pushing the Save to a Task twice (once for the original Task and a second time in the helper). 这更像是我要达到的结果,但它看起来很麻烦,而且助手似乎两次将“保存到任务”推入一次(原始任务一次,而助手中第二次)。

Is there a more simple way to do this conversion from a Task to a Task of T? 有没有更简单的方法可以完成从任务到任务T的转换?

I don't see a point of such helper method, but if you really want you can like this: 我看不到这种辅助方法的要点,但是如果您真的想要,可以这样:

public static class Helper<T> where T : ICanSave {
    public static async Task<T> Save(T obj) {
        await obj.Save();
        return obj;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM