【问题标题】:C# How to turn an Action of T into awaitable Function of Task of TC#如何将T的Action变成T的Task的可等待函数
【发布时间】:2018-09-17 11:18:05
【问题描述】:

我希望能够将一些方法保存为操作及其对应的异步对应项。为此,我需要将它们变成Func<Task>

我已经搞定了。

public class Class1 {
    Action myAction;
    Func<Task> myFunc;

    public Class1() {
        // for demo purposes I use a local method
        void MyVoidMethod() {
            // some code
        }
        myAction = MyVoidMethod;
        myFunc = () => Task.Factory.StartNew(myAction);
    }

    public async void AnotherMethod() {
        // later in async some method
        await myFunc.Invoke();
    }
}

但是当我还想要一个可选的输入参数(例如报告异步函数中的进度)时,我该如何声明呢?我不明白语法是如何工作的。

public class Class2 {
    Action<IProgress<bool>> myAction;
    Func<Task<IProgress<bool>>> myFunc;

    public Class2() {
        void MyVoidMethod(IProgress<bool> prog = null) {
            // some code
        }
        myAction = MyVoidMethod;
        // line below gives squiggelies under `myAction`
        myFunc = () => Task.Factory.StartNew(myAction);
    }

    public async void AnotherMethod() {
        // later in async some method
        var prog = new Progress<bool>();
        prog.ProgressChanged += (s, e) => {
            // do something with e
        };
        await myFunc.Invoke(prog);
    }
}

【问题讨论】:

  • 您可能会混淆Action&lt;T&gt;,它将T 作为输入参数,而Task&lt;T&gt; 返回一个T 作为结果。除此之外,不要声明async void 方法。始终使用async Task

标签: c# async-await delegates func


【解决方案1】:

您正在定义 myFunc 以接收一个 Task 而不是返回一个,您需要定义该 func 以接收 IProgress 并返回一个 Task 作为结果。

Func<IProgress<bool>, Task> myFunc;

然后你需要将进度传递给你的 lambda 中的执行方法

this.myFunc = p => Task.Factory.StartNew(() => this.MyVoidMethod(p))

而您的另一个方法需要将进度作为参数

public async void AnotherMethod(IProgress<bool> progress)
{
    await this.myFunc.Invoke(progress);
}

【讨论】:

  • 谢谢,这行得通。我把事情搞糊涂了。当然我不想返回某种类型的任务;只是一个任务。我已经编辑了我的问题以正确显示 Progress 对象和事件的使用,因为 AnotherMethod 不一定需要这些输入参数。要添加到您的答案中,此行也可以使用:this.myFunc = p =&gt; Task.Factory.StartNew(() =&gt; this.myAction.Invoke(p));
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多