Files
Common-VS2019/SacsMobileMaui/Maui/Utils/SamThreadUtil.cs
T

70 lines
1.9 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sarand.Net.Mobile.Maui.Utils
{
//=======================================================================
public static class SamThreadUtil
{
//-------------------------------------------------------------------
// Thread utilities.
//-------------------------------------------------------------------
/// <summary>Is the current thread the main thread.</summary>
public static bool IsMainThread()
{
return MainThread.IsMainThread;
}
//-------------------------------------------------------------------
// 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
//-------------------------------------------------------------------
/// <summary>Invoke task on main thread.</summary>
public static void InvokeOnMainThread(Action taskFn)
{
MainThread.BeginInvokeOnMainThread(() =>
{
taskFn();
});
}
/// <summary>Invoke task on main thread and wait for completion.</summary>
public static void InvokeOnMainThreadSync(Action taskFn)
{
var tcs = new TaskCompletionSource<Object>();
MainThread.BeginInvokeOnMainThread(() =>
{
try
{
taskFn();
tcs.SetResult(true);
}
catch (Exception ex) { tcs.SetException(ex); }
});
}
/// <summary>Invoke task on main thread and wait for completion.</summary>
public static T InvokeOnMainThreadSync<T>(Func<T> taskFn)
{
var tcs = new TaskCompletionSource<T>();
MainThread.BeginInvokeOnMainThread(() =>
{
try
{
var result = taskFn();
tcs.SetResult(result);
}
catch (Exception ex) { tcs.SetException(ex); }
});
return tcs.Task.Result;
}
//-------------------------------------------------------------------
}
//=======================================================================
}