gpt4 book ai didi

c# - Microsoft.Graph GetAsync() 无限期挂起

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

简介

我正在开发一个 ASP.NET 应用程序,除其他外,该应用程序应该从 Azure Active Directory 检索用户。为此,我使用 Microsoft Graph 版本 1.14.0 预览库,可以在 here 找到该库。 .

由于该库仅提供用于检索用户的异步方法,因此我使用以下(伪)代码来同步运行它。

string userPrincipalName = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a4d0c1d7d08ad1d7c1d6e4cdcad0d1cac1c2cbd6c1c0d1c7c5d0cdcbca8ac7cbc9" rel="noreferrer noopener nofollow">[email protected]</a>";
var task = Task.Run(async () => await _graphServiceClient.Users[userPrincipalName].Request().GetAsync());

while (!task.IsCompleted)
Thread.Sleep(200);

User retrievedUser = task.Result;

问题

我现在面临的问题是,从 ASP.NET 应用程序调用这段代码后,task.IsCompleted 永远保持 false。现在有一个我无法理解的奇怪部分:代码在控制台应用程序和单元测试(使用 NUnit)中都完美运行。

有人可能认为 GraphServiceClient 实例在这些版本中的构建方式不同,但我 100% 肯定事实并非如此。构成它的信息是从数据库加载的,单元测试中的代码与 ASP.NET 应用程序 Controller 中的代码完全相同。使用单元测试,上述代码的执行时间约为 1.5 秒。在 ASP.NET 应用程序中,我让它运行了长达 30 分钟,没有任何结果、没有错误、没有超时,什么也没有。

我意识到这可能是一个小问题,但我确实希望有人遇到同样的问题并能够解决它。

更新

我设法解决了这个问题。奇怪的是,将我的所有方法转换为异步任务不起作用,因为甚至 await 仍然挂起。然而,我并不完全理解为什么我的解决方案现在有效。看来我的伪代码并不完全准确,解决方案就在其中。

尝试#1(不起作用)

此代码永远保留在 while (!runTask.IsCompleted) 中。

object GetResult<TResult>(Task<TResult> task)
{
using (task)
using (var runTask = Task.Run(async () => await task))
{
while (!runTask.IsCompleted)
Thread.Sleep(SleepTime);

if (runTask.Exception != null)
throw runTask.Exception.InnerException ?? runTask.Exception;

return runTask.Result;
}
}

User GetUser(string userPrincipalName)
{
return (User)GetResult(_graphServiceClient.Users[userPrincipalName].Request().GetAsync());
}

尝试#2(不起作用)

此方法在执行 await 行后保持挂起。

async Task<User> GetUser(string userPrincipalName)
{
User user = await _graphServiceClient.Users[userPrincipalName].Request().GetAsync();
return user;
}

尝试#3(有效)

这段代码与尝试#1中的代码基本相同,唯一的区别是它没有使用GetResult方法,但它确实使用了与GetResult完全相同的方法.

User GetUser(string userPrincipalName)
{
using(var task = Task.Run(async () => await _graphServiceClient.Users[userPrincipalName].Request().GetAsync()))
{
while (!task.IsCompleted)
Thread.Sleep(200);

return task.Result;
}
}

虽然这种方法可能不被认为是最佳实践,但它确实有效。我非常困惑为什么这种方法有效,因为尝试 #1 中的代码不起作用,而且它实际上是相同的代码。谁能解释一下这是为什么吗?

最佳答案

我遇到了同样的问题( see here )。我通过恢复 Microsoft.GraphMicrosoft.Graph.Core 版本 1.12.0 解决了这个问题。

关于c# - Microsoft.Graph GetAsync() 无限期挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55105321/

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