无法在未调用Looper.prepare()[xamarin]的线程内创建处理程序

Dbl*_*Dbl 5 xamarin xamarin.forms

所以我实际上没有问题,因为我已经解决了它,但是如果其他人遇到这个问题,总是很高兴有一个简洁的解决方案.

虽然有很多"Can't create handler inside thread which has not called Looper.prepare()"- 问题没有用xamarin标记.(所以他们都是java,我有0个匹配"无法在线程中创建处理程序,而没有调用Looper.prepare()[xamarin]")

Mau*_*mar 9

生成该问题的原因是您尝试从其他线程开始在UI上工作.如果要更改UI,必须从UI线程调用UI更改.

Xamarin Android:

activity.RunOnUiThread(() =>
{
      // Write your code here         
});
Run Code Online (Sandbox Code Playgroud)

Xamarin IOS:

nsObject.BeginInvokeOnMainThread(() =>
{
     // Write your code here                
});
Run Code Online (Sandbox Code Playgroud)

Xamarin表格:

Device.BeginInvokeOnMainThread(() =>
{
     // Write your code here
}
Run Code Online (Sandbox Code Playgroud)


Dbl*_*Dbl 8

public static class PageExtensions
{
    public static Task<bool> DisplayAlertOnUi(this Page source, string title, string message, string accept, string cancel)
    {
        TaskCompletionSource<bool> doneSource = new TaskCompletionSource<bool>();
        Device.BeginInvokeOnMainThread(async () =>
        {
            try
            {
                var result = await source.DisplayAlert(title, message, accept, cancel);
                doneSource.SetResult(result);
            }
            catch (Exception ex)
            {
                doneSource.SetException(ex);
            }
        });

        return doneSource.Task;
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,我有一个使用TaskCompletionSource来解决问题的案例.