如何有条件地让“异步任务”方法成为无操作?

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

为了将文本写入 SQL Server XEvent 配置文件,我编写了以下方法:

protected async Task LogToProfiler(string message)
{
    await using (var dbContext = await NoTrackingDbFactory.CreateDbContextAsync())
    {
        await dbContext.Database.ExecuteSqlAsync($"-- {message}");
    }
}

效果很好,可以将我想要的消息写到探查器事件列表中。问题是,我需要的是:

#if DEBUG
protected async Task LogToProfiler(string message)
{
    await using (var dbContext = await NoTrackingDbFactory.CreateDbContextAsync())
    {
        await dbContext.Database.ExecuteSqlAsync($"-- {message}");
    }
}
#else
protected void LogToProfiler(string message) {}
#end

因此,在发布模式下,不存在

Task
的设置和拆卸。有办法做到这一点吗?

另外,我将其称为:

if (profilingOn)
    await LogToProfiler("entering method");

如果 profilingOn == false,这是否足以避免安装/拆卸?我相信是的。使用

#if DEBUG
更安全,但如果它是为
profilingOn
构建的,我可以强制
RELEASE
为 false。

我最关心的是开发人员会犯错误,因此即使 profilingOn 为 false 并且我们在

RELEASE
模式下运行,它最终也可能会被调用。所以我想尽可能安全。

c# async-await
1个回答
-2
投票

您可以对所有日志方法执行类似的操作:

protected async Task LogToProfiler(Func<string> messageProvider)
{
    if(!profilerEnabled) 
       return; //as you might know this section up to await will be called synchronously.
    var message = messageProvider();
    await using (var dbContext = await NoTrackingDbFactory.CreateDbContextAsync())
    {
        await dbContext.Database.ExecuteSqlAsync($"-- {message}");
    }
}

await
方法中第一个
async
之前的所有内容都是在同一线程上同步调用的。不管怎样,Task都会被返回,但它会是Task.CompleteTask,它是单例的。

© www.soinside.com 2019 - 2024. All rights reserved.