首页 > 解决方案 > 使用静态 lambda 启动任务

问题描述

我找到了这篇文章 并想在我的代码中重构一些以确保只使用静态 lambda。但是我不知道如何使 lambda 静态化,如果它是另一种方法的无参数 Func。

例如: 的定义public Task StartNew(Action action);包含一个 Action,它是一个无参数的 lambda。我的电话是:Task.Factory.StartNew(() => parser.AnswerOnRequest(config, request)); 正如博文所说,这会生成非静态类,这些类总是为每次调用生成一个新对象,我希望(出于学习目的)避免这种情况。

现在我编写了以下静态方法:

private static async void ExecuteAnswerOnRequest(TXRequestParser parser,
    AppMsgConfiguration config,
    VdvKaLogic.Implementation.SoapReqMsg01V03 request,
    Func<TXRequestParser, AppMsgConfiguration, VdvKaLogic.Implementation.SoapReqMsg01V03, Task> answerOnRequest) 
{
    await answerOnRequest(parser, config, request);
}

并称之为:

ExecuteAnswerOnRequest(parser, config, request,
    static async (parser, config, request) => await parser.AnswerOnRequest(config, request));

但不知何故,Task与堆栈不平行。

现在我想知道Task.Factory.StartNew如果给定的 lambda 是无参数的,如何使 lambda 成为静态的。

标签: c#performancelambdastatictask

解决方案


推荐阅读