Error in Xamarin Android with a progress dialog “Only the original thread that created a view hierarchy can touch its views”

后端 未结 4 1359
醉酒成梦
醉酒成梦 2021-01-25 08:01

I\'m trying to use a progress dialog, while filling a datagrid, but I get the following error: \"Only the original thread that created a view hierarchy can touch its views\", th

相关标签:
4条回答
  • 2021-01-25 08:48

    The error is telling you the app's UI must be handled by the main thread. In your code, you are running some code on a background thread (ThreadPool.QueueUserWorkItem) that needs to be run on the UI thread (RunOnUiThread) instead.

    0 讨论(0)
  • 2021-01-25 08:57

    you cannot use dlg.Dismiss(); inside ThreadPool.QueueUserWorkItem, move it before try close sign

    0 讨论(0)
  • 2021-01-25 08:58

    why not use Task instead?

    Task.Run(() => doStuff("hello world"));
    

    It doesn't really seem a lot better, but at least it doesn't have an unused identifier.

    Note: Task.Run() is .Net 4.5 or later. If you're using .Net 4 you have to do:

    Task.Factory.StartNew(() => doStuff("hello world"));
    

    Both of the above do use the thread pool.

    0 讨论(0)
  • 2021-01-25 08:59

    Only the original thread that created a view hierarchy can touch its views

    As @CaPorter said, the app's UI must be handled by the main thread. There are any number of ways to get code to execute on the UI thread, you could try using Looper.MainLooper with Handler.Post().

    Modify your code like this :

    ThreadPool.QueueUserWorkItem(d => {
    
        ...
    
        Handler handler = new Handler(Looper.MainLooper);
        Action action = () =>
        { 
            dataGrid.ItemsSource = lst;
            dlg.Dismiss();
        };
        handler.Post(action);
    });
    
    0 讨论(0)
提交回复
热议问题