我有一个异步函数,我想在任务完成后解除ProgressDialog。我看到它是在onPostExecute方法中完成的,但是我没有异步类来实现它。在我的例子中,它是异步方法
public async void ScanBarcode()
{
dialogIndicator.Show ();
var zscanner = new MobileBarcodeScanner();
//var result = await zscanner.Scan();
var result = await zscanner.Scan ();
HandleScanResult(result);
}
void HandleScanResult(ZXing.Result result)
{
dialogIndicator.Dismiss ();
}
App会为dialogIndicator.Dismiss();抛出异常。我得到了
"Android.Util.AndroidRuntimeException: Only the original thread that created a view hierarchy can touch its views.
at --- End of managed exception stack trace ---
at android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:7155)
at at android.view.ViewRootImpl.doDie(ViewRootImpl.java:6255)
at at android.view.ViewRootImpl.die(ViewRootImpl.java:6240)
at at android.view.WindowManagerGlobal.removeViewLocked(WindowManagerGlobal.java:365)
at at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:320)
at at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:84)
at at android.app.Dialog.dismissDialog(Dialog.java:420)
at at android.app.Dialog$1.run(Dialog.java:128)
at at android.os.Handler.handleCallback(Handler.java:733)
at at android.os.Handler.dispatchMessage(Handler.java:95)
at at android.os.Looper.loop(Looper.java:146)
at at android.app.ActivityThread.main(ActivityThread.java:5731)
at at java.lang.reflect.Method.invokeNative(Native Method)
at at java.lang.reflect.Method.invoke(Method.java:515)
at at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
在这种情况下如何解除ProgressDialog。
答案 0 :(得分:0)
知道抛出什么类型的异常以查看出错的地方会很有用。
我建议您更改代码中的某些内容。
首先,将async
与void
返回类型一起使用不是最佳做法。因为这使得无法等待ScanBarcode
或从那里捕获任何例外。
第二件事是你没有在HandleScanResult
内做任何无法在ScanBarcode
内完成的事情。所以我会将其合并到以下内容中:
public async Task ScanBarcode()
{
dialogIndicator.Show ();
var zscanner = new MobileBarcodeScanner();
var result = await zscanner.Scan ();
dialogIndicator.Dismiss ();
}
这样代码"等待"对于扫描结果,然后将解除dialogIndicator。
如果从除UI线程之外的其他线程调用ScanBarcode
,您可以在UI线程上强制执行,如下所示:
public async Task ScanBarcode()
{
RunOnUiThread(()=>
{
dialogIndicator.Show ();
});
var zscanner = new MobileBarcodeScanner();
var result = await zscanner.Scan ();
RunOnUiThread(()=>
{
dialogIndicator.Dismiss ();
});
}