gpt4 book ai didi

c# - 异常 : The application called an interface that was marshalled for a different thread

转载 作者:行者123 更新时间:2023-11-30 20:02:00 29 4
gpt4 key购买 nike

private void LogInButton_Click(object sender, RoutedEventArgs e)
{
var api = new RestAPI("http://localhost:2624/", UsernameTextBox.Text, PasswordTextBox.Password);

api.AutenticarUsuarioFinalizado += (o, args) =>
{
ProgressBar.IsIndeterminate = false;
ProgressBar.Visibility = Visibility.Collapsed;
LogInButton.IsEnabled = true;

if (args.Error) return;

if (args.Resultado.Autenticado)
{
}
};

api.AutenticarUsuario();
ProgressBar.Visibility = Visibility.Visible;
ProgressBar.IsIndeterminate = true;
LogInButton.IsEnabled = false;
}

api.AutenticarUsuario(); 异步调用 rest API,完成后调用事件处理程序 api.AutenticarUsuarioFinalizado 并在 ProgressBar 行中收到此错误.IsIndeterminate = false; 因为调用打开了一个新线程,我该如何解决?错误是:

应用程序调用了为不同线程编码的接口(interface)。

最佳答案

问题是您的事件处理程序没有在 UI 线程上执行。我认为解决此问题的最佳方法是使用 TaskCompletionSource 将 EAP(基于事件的异步模式)方法转换为 TAP(基于任务的异步模式):

public static Task<Resultado> AutenticarUsuarioAsync(this RestAPI api)
{
var tcs = new TaskCompletionSource<Resultado>();

api.AutenticarUsuarioFinalizado += (sender, args) =>
{
if (args.Error)
tcs.TrySetException(new SomeAppropriateException());
else
tcs.TrySetResult(args.Resultado);
};

api.AutenticarUsuario();

return tcs.Task;
}



private async void LogInButton_Click(object sender, RoutedEventArgs e)
{
var api = new RestAPI(
"http://localhost:2624/", UsernameTextBox.Text,
PasswordTextBox.Password);

ProgressBar.Visibility = Visibility.Visible;
ProgressBar.IsIndeterminate = true;
LogInButton.IsEnabled = false;

try
{
var resultado = await api.AutenticarUsuarioAsync();
if (resultado.Autenticado)
{
// whatever
}
}
catch (SomeAppropriateException ex)
{
// handle the exception here
}
finally
{
ProgressBar.IsIndeterminate = false;
ProgressBar.Visibility = Visibility.Collapsed;
LogInButton.IsEnabled = true;
}
}

因为 awaitTask 将始终在原始上下文中恢复,所以您不会以这种方式获得异常。作为一个额外的优势,您不必像使用 EAP 那样“由内而外”地编写代码。

您还应该考虑使用绑定(bind),而不是手动设置 UI 控件的属性。

关于c# - 异常 : The application called an interface that was marshalled for a different thread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17245512/

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