C# 从AAD窗口的另一个线程和类访问UI线程窗口
我正在构建一个WPF,提示用户登录Azure AD,但我无法获得fire调用,而是挂起UI线程。这是我试图调用的代码C# 从AAD窗口的另一个线程和类访问UI线程窗口,c#,wpf,async-await,azure-active-directory,microsoft-graph-api,C#,Wpf,Async Await,Azure Active Directory,Microsoft Graph Api,我正在构建一个WPF,提示用户登录Azure AD,但我无法获得fire调用,而是挂起UI线程。这是我试图调用的代码 authResult = _application.AcquireTokenInteractive(_scopes) .WithParentActivityOrWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle)
authResult = _application.AcquireTokenInteractive(_scopes)
.WithParentActivityOrWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle)
.ExecuteAsync().Result;
我试着把它包装在调度员的电话里,就像这样
internal static Dispatcher GetDispatcher(this DispatcherObject source)
{
//use the application's dispatcher by default
if (Application.Current != null) return Application.Current.Dispatcher;
//fallback for WinForms environments
if (source.Dispatcher != null) return source.Dispatcher;
// ultimately use the thread's dispatcher
return Dispatcher.CurrentDispatcher;
}
var dispatcher = MainWindow.main.GetDispatcher();
if (!dispatcher.CheckAccess())
{
var action = new Action(() => {
authResult = _application.AcquireTokenInteractive(_scopes)
.WithParentActivityOrWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle)
.ExecuteAsync().Result;
});
dispatcher.Invoke(DispatcherPriority.Normal, action);
return;
}
如果我在MainWindow.xaml.cs中移动交互式调用,它可以正常工作,但我希望将其移动到服务类来清理。我可能做错了什么?上面的代码在一个具有如下签名的函数中
public async Task AuthenticateRequestAsync(HttpRequestMessage request)
如果需要,我可以提供其他信息
_application.AcquireTokenInteractive(_scopes)
.WithParentActivityOrWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle)
.ExecuteAsync().Result;
调用结果将阻止UI线程。
相反,你需要等待电话
await _application.AcquireTokenInteractive(_scopes)
.WithParentActivityOrWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle)
.ExecuteAsync();
您还需要将函数标记为async
调用结果将阻止UI线程。
相反,你需要等待电话
await _application.AcquireTokenInteractive(_scopes)
.WithParentActivityOrWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle)
.ExecuteAsync();
您还需要将函数
标记为async
看看朱纳斯的解决方案。此外,如果您决定将该代码放入库中,请考虑使用.CuffulaAsAuto(FALSE)来避免不必要的情况。用一些例子来讨论它。看看朱纳斯的解决方案。此外,如果您决定将该代码放入库中,请考虑使用.CuffulaAsAuto(FALSE)来避免不必要的情况。用一些例子来讨论它。ExecuteAsync()。结果
这在几个层面上看起来很奇怪(而且可能很危险)。如果一直使用async and Wait模式,则不必调用Result
,它将在UI线程上创建一个延续。这只是一个猜测,但我认为从服务调用调度程序时,调度程序会有所不同。确保使用Application Dispatcher来确保使用的是UI Dispatcher。ExecuteAsync()。结果
这在某些级别上看起来很奇怪(而且可能很危险)。如果一直使用async and Wait模式,则不必调用Result
,它将在UI线程上创建一个延续。这只是一个猜测,但我认为从服务调用调度程序时,调度程序会有所不同。请确保您使用应用程序调度程序来确保您使用的是UI调度程序。谢谢,因此,如果调用该程序的代码对我有用,谢谢!现在有两次打电话的问题,但我认为这是其他地方的问题。将此标记为答案。谢谢,如果调用此的代码对我有用,谢谢!现在有两次打电话的问题,但我认为这是其他地方的问题。将此标记为答案。