gpt4 book ai didi

c# - 处理异步函数的空响应的正确方法是什么?

转载 作者:太空宇宙 更新时间:2023-11-03 20:57:13 24 4
gpt4 key购买 nike

我正在开发一个 Azure 函数,它与我的表进行通信并更新表中的数据。我最近发现 Microsoft.WindowsAzure.Storage 包现在只有 Async 函数,而我对这些函数并不熟悉。

在我用于测试的函数中,如果该行存在,我想返回 true,如果不存在,则返回 false。如果该行存在,它就可以工作,但如果该行不存在,程序就会挂起(因为它正在等待响应)。

有人可以帮助我吗?

这是我的代码:

public static bool rowExists(CloudTable table, string city, string state)
{
TableOperation tOP = TableOperation.Retrieve<SickCity>(city, state);
Task<TableResult> result = table.ExecuteAsync(tOP);
if (result == null)
return false;
else
return true;
}

编辑:

这是我调用 rowExists 的地方

log.Info($"Does the row \"New York, NY\" exist? {rowExists(sickTable, "New York", "NY")}");

最佳答案

您没有得到预期的结果,因为您的代码没有等待异步请求完成。您需要稍微更改一下函数才能正确调用 ExecuteAsync :

public static async Task<bool> rowExists(CloudTable table, string city, string state)
{
TableOperation tOP = TableOperation.Retrieve<SickCity>(city, state);
var result = await table.ExecuteAsync(tOP);

if (result == null)
return false;
else
return true;
}

ExecuteAsync返回 Task ,直到将来某个时间(异步操作完成时)才会包含实际结果。 await关键字将导致您的代码在该行“暂停”并等待 ExecuteAsync任务包含实际值。然后你的逻辑就可以继续。

请注意,方法签名已更改:现在是 async Task<bool> rowExists 。您的方法现在返回 Task同样,这意味着调用 this 方法的代码也必须使用 await 。这是处理数据库和网络调用等异步操作的常见模式。

如果这看起来很奇怪,您可以在此处阅读有关异步/等待模式的更多信息:

关于c# - 处理异步函数的空响应的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49281924/

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