Files
Common-VS2019/SacsStandardMob/Mobile/Tasks/SaxThreadUtil.cs
T
2021-05-05 15:36:28 +01:00

48 lines
1.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace Sarand.Net.Standard.Mobile.Tasks
{
//=======================================================================
public static class SaxThreadUtil
{
//-------------------------------------------------------------------
// I n v o k e o n M a i n T h r e a d a n d W a i t
//-------------------------------------------------------------------
// Invoke task on main thread and wait for completion.
public static void BeginInvokeOnMainThreadSync (Action taskFn)
{
var tcs = new TaskCompletionSource<Object>();
Device.BeginInvokeOnMainThread(() =>
{
try
{
taskFn();
tcs.SetResult(null);
}
catch (Exception ex) { tcs.SetException(ex); }
});
}
public static T BeginInvokeOnMainThreadSync<T> (Func<T> taskFn)
{
var tcs = new TaskCompletionSource<T>();
Device.BeginInvokeOnMainThread(() =>
{
try
{
var result = taskFn();
tcs.SetResult(result);
}
catch (Exception ex) { tcs.SetException(ex); }
});
return tcs.Task.Result;
}
//-------------------------------------------------------------------
}
//=======================================================================
}