如何中途停止函数并让调用方执行一些任务,获取结果并继续在 C# 中完成函数的其余工作



我当前的场景是,我正在用C#编写一个库,用于执行一些任务。但任务需要先运行,然后运行到一半,它需要调用方的一些输入,然后才能在同一函数中继续执行其余任务。我如何才能实现这种场景,因为我不确定应该搜索什么关键字。

例如,在库中有一个函数:

public bool DoSomething()
{
SomeWorkToBeDoneByLibrary_1();
SomeWorkToBeDoneByLibrary_2();
SomeWorkToBeDoneByLibrary_3();
// the caller now needs to perform a job and return a result before the library function can proceed
// the caller is the application consuming the library
string result = SomeWorkToBeDoneByCaller(); // ***How to achieve this?
SomeWorkToBeDoneByLibrary_4(result);
SomeWorkToBeDoneByLibrary_5(result);
SomeWorkToBeDoneByLibrary_6(result);
return true;
}

您可以传入Func<string>回调参数:

public bool DoSomething(Func<string> someWorkToBeDoneByCaller)
{
SomeWorkToBeDoneByLibrary_1();
SomeWorkToBeDoneByLibrary_2();
SomeWorkToBeDoneByLibrary_3();
// the caller now needs to perform a job and return a result before the library function can proceed
// the caller is the application consuming the library
string result = someWorkToBeDoneByCaller();
SomeWorkToBeDoneByLibrary_4(result);
SomeWorkToBeDoneByLibrary_5(result);
SomeWorkToBeDoneByLibrary_6(result);
return true;
}

然后电话看起来像:

libobj.DoSomething(() => "foo");

libobj.DoSomething(MyFunc);
string MyFunc() { return "foo"; }

有关Func<T>的详细信息,请点击此处:https://learn.microsoft.com/en-us/dotnet/api/system.func-1

有几种方法可以实现这一点。一种是将调用者输入方法

public bool DoSomething(MyClass callerClass)
{
SomeWorkToBeDoneByLibrary_1();
SomeWorkToBeDoneByLibrary_2();
SomeWorkToBeDoneByLibrary_3();
string result = callerClass.SomeWorkToBeDoneByCaller(); 
SomeWorkToBeDoneByLibrary_4(result);
SomeWorkToBeDoneByLibrary_5(result);
SomeWorkToBeDoneByLibrary_6(result);
return true;
}

我已经在一些事情上使用了上面的模式,根据您的用例,它可以做到这一点(根据工作的性质,我建议也让它异步,但这是另一回事(

另一种方法是传入委托方法(更改<>参数以更改方法的签名,如果方法返回void则使用Action(

public bool DoSomething(Func<ReturnClass,string,string> methodFromCallerClass)
{
SomeWorkToBeDoneByLibrary_1();
SomeWorkToBeDoneByLibrary_2();
SomeWorkToBeDoneByLibrary_3();
string result = methodFromCallerClass("foo","Bar"); 
SomeWorkToBeDoneByLibrary_4(result);
SomeWorkToBeDoneByLibrary_5(result);
SomeWorkToBeDoneByLibrary_6(result);
return true;
}

如果签名不100%匹配,则可以使用linq使传递委托变得更容易,例如(x,y(=>Foo(x,y,"bar"(将方法从三个参数改为两个

最新更新