C#如何将T的动作转换为T的任务的等待函数

问题描述 投票:-1回答:1

我希望能够将一些方法保存为动作及其相应的异步对应方。为此,我需要将它们变成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();
    }
}

但是,当我还想要一个可选的输入参数来报告async Func的进度时,如何声明这个?我不明白语法是如何工作的。

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);
    }
}
c# async-await delegates func
1个回答
1
投票

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

Func<IProgress<bool>, Task> myFunc;

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

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

而你的AnotherMethod需要将Progress in作为参数

public async void AnotherMethod(IProgress<bool> progress)
{
    await this.myFunc.Invoke(progress);
}
© www.soinside.com 2019 - 2024. All rights reserved.