Xamarin.Forms - BeginInvokeOnMainThread for an async Action

后端 未结 3 1923
我寻月下人不归
我寻月下人不归 2021-01-19 01:02

I am familiar with the rules about updating UI elements on the UI thread using the Device.BeginInvokeOnMainThread, however I have an operation that needs to be run on the UI

3条回答
  •  感情败类
    2021-01-19 01:27

    Dropping this here in case someone wants to await the end of an action which has to be executed on the main thread

    public static class DeviceHelper
    {
        public static Task RunOnMainThreadAsync(Action action)
        {
            var tcs = new TaskCompletionSource();
            Device.BeginInvokeOnMainThread(
                () =>
                {
                    try
                    {
                        action();
                        tcs.SetResult(null);
                    }
                    catch (Exception e)
                    {
                        tcs.SetException(e);
                    }
                });
    
            return tcs.Task;
        }
    
        public static Task RunOnMainThreadAsync(Task action)
        {
            var tcs = new TaskCompletionSource();
            Device.BeginInvokeOnMainThread(
                async () =>
                {
                    try
                    {
                        await action;
                        tcs.SetResult(null);
                    }
                    catch (Exception e)
                    {
                        tcs.SetException(e);
                    }
                });
    
            return tcs.Task;
        }
    }
    
        

    提交回复
    热议问题