转换任务<a> to Task<b> asynchronously</b></a>

时间:2014-12-05 12:29:09

标签: c# asp.net asynchronous task

我正在将内部身份验证服务与MembershipProvider集成。自定义提供商:

    public override MembershipUser CreateUser(
        string username,
        string password,
        string email,
        string passwordQuestion,
        string passwordAnswer,
        bool isApproved,
        object providerUserKey,
        out MembershipCreateStatus status)
    {

        //var res = client.Register(username, password, email);
        //status = MembershipCreateStatus.Success; // conver to Mem
        return null;

问题出在客户端。 如何将一项任务转换为另一项?

    public async Task<MembershipUser> Register(string username, string password, string email, bool isStaff=false)
    {
        var task = serviceFoo.Register(username, password, email, isStaff);
        // TODO Task<RegisteredUser> -> Task<MembershipUser>
        //var convertedTask = task.
        //return new Task<MembershipUser>();
    }

我想:

  • 异步执行
  • 我不希望提供商看到RegisteredUser。

我会为RegUser写一个扩展方法进行对话,但我不知道如何异步转换任务。

2 个答案:

答案 0 :(得分:4)

看起来您实际上想要从Task<RegisteredUser>转换为Task<MembershipUser>,您想要从RegisteredUser转换为MembershipUser,假设您拥有你提到的转换扩展方法,只需这样做:

public async Task<MembershipUser> Register(string username, string password, string email, bool isStaff=false)
{
        var user = await serviceFoo.Register(username, password, email, isStaff);// user is RegisteredUser
        return user.ConvertTomembershipUser();

}

答案 1 :(得分:1)

任务没有内置构图功能。幸运的是,实施

是微不足道的
public static async Task<TResult> flatmap<TSource, TResult>(this Task<TSource> src, Func<TSource, Task<TResult>> f) {
  return await f(await src);
}

public static async Task<TResult> map<TSource, TResult>(this Task<TSource> src, Func<TSource, TResult> f) {
  return f(await src);
}