Can't create handler inside thread which has not called Looper.prepare() [xamarin]

倖福魔咒の 提交于 2020-08-24 08:07:12

问题


So i don't actually have a question because i've already solved it, but in case someone else runs into this issue it's always nice to have a neat solution.

And while there is a plentitude of "Can't create handler inside thread which has not called Looper.prepare()" - questions there is none tagged with xamarin. (so theirs is all java and i had 0 matches for "Can't create handler inside thread which has not called Looper.prepare() [xamarin]")


回答1:


The issue is generated because You tried to do work on UI from other thread. If you want to change UI, Must call UI changes from UI thread.

Xamarin Android:

activity.RunOnUiThread(() =>
{
      // Write your code here         
});

Xamarin IOS:

nsObject.BeginInvokeOnMainThread(() =>
{
     // Write your code here                
});

Xamarin Forms:

Device.BeginInvokeOnMainThread(() =>
{
     // Write your code here
}



回答2:


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;
    }
}

Finally i had a case for using TaskCompletionSource to solve an issue.



来源:https://stackoverflow.com/questions/33484357/cant-create-handler-inside-thread-which-has-not-called-looper-prepare-xamari

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!