gpt4 book ai didi

c# - 尝试从 C# 异步调用长时间运行的存储过程时失败

转载 作者:太空宇宙 更新时间:2023-11-03 22:30:14 25 4
gpt4 key购买 nike

我有一个长时间运行的存储过程,spLongRunningProcess,当我使用 Async Await 调用它时,它运行并执行得很好,但是我需要在不等待响应的情况下调用它,因为它是一个运行时间非常长的过程。这是我的下面的代码我遗漏了一些东西,但不能完全确定。

public async Task<ResultObject> LongSPCallAsync()
{
ResultObject ro = new ResultObject();
try
{
using (_context = new DbContext())
{
SqlParameter returnVal2 = new SqlParameter("@ReturnVal2", SqlDbType.Int)
{
Direction = ParameterDirection.Output
};

_context.Database.ExecuteSqlCommandAsync("EXEC @ReturnVal2 = [spLongRunningProcess]", returnVal2).ConfigureAwait(false); //<-- This NEVER runs unless I await it.?
var oooo = returnVal2.Value; //<-- just orphan code for debugging.
}
}
catch (Exception e)
{
await _logService.AddLogAsync(e, $"Error running SP:", "spLongRunningProcess");
}
return ro;
}

在我指定的 Conn 字符串中 (Asynchronous Processing=True)

为了验证它是否真的在运行,我只是通过另一个进程检查数据库。只是寻找我错过的东西。

最佳答案

您应该等待调用ExecuteSqlCommandAsync:

await _context.Database.ExecuteSqlCommandAsync(...).ConfigureAwait(false);

await 语句被执行时,LongSPCallAsync() 将返回并且调用线程可以继续做其他事情直到 SQL 命令被执行并且剩下的方法被执行。

您可以选择不等待 LongSPCallAsync(),但您需要等待 ExecuteSqlCommandAsync() 才能使 DbContext 不被等待在命令完成之前释放。此外,如果您不等待 ExecuteSqlCommandAsync(),您将无法捕获并记录由此抛出的任何异常。

关于c# - 尝试从 C# 异步调用长时间运行的存储过程时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58238290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com