问题描述
我有方法
public async Task doSomething()
在方法中,我有代码:
ShowSpinner();
await System.Threading.Tasks.Task.Run(() =>
{
try
{
getValue = value();
}
catch(Exception ex)
{
}
finally
{
HideSpinner();
}
});
ShowSpinner()
和 HideSpinner()
只是叠加层,可以防止用户与屏幕进行交互并显示旋转轮以指示加载.
The ShowSpinner()
and HideSpinner()
are simply overlays to prevent the user from interacting with the screen and show a spinning wheel to indicate loading.
我遇到了错误:
我知道这是由于 HideSpinner()
引起的.如何解决此一致性错误?
I know that this is because of the HideSpinner()
. How can I get around this consistency error?
推荐答案
在这里您可以做两件事,首选方法是在try finally块中等待任务,第二种不太受欢迎的方法是将您的 HideSpinner();
包裹在 RunOnUiThread
中.
There are two things you can do here, the preferred method would be to await your task inside a try finally block, and the second less preferred method would be to wrap your HideSpinner();
in a RunOnUiThread
.
ShowSpinner();
try
{
var val = await Task.Run(() => "foo");
// for a little added performance,
// if val isn't being marshalled to the UI
// you can use .ConfigureAwait(false);
// var val = await Task.Run(() => "foo").ConfigureAwait(false);
}
catch { /* gulp */}
finally { HideSpinner(); }
不太受欢迎
ShowSpinner();
await Task.Run(() =>
{
try
{
var val = "value";
}
catch { /* gulp */ }
finally
{
InvokeOnMainThread(() =>
{
HideSpinner();
});
}
});
这篇关于等待任务的UIKITThreadAccessException.使用try-catch-finally块运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!