using System.Threading.Tasks;
using static System.Application.Services.IMainThreadPlatformService;
namespace System.Application
{
///
/// 适用于桌面端的主线程帮助类,参考 Xamarin.Essentials.MainThread
///
///
///
public static class MainThreadDesktop
{
public static bool IsMainThread => Instance.PlatformIsMainThread;
public static void BeginInvokeOnMainThread(Action action, DispatcherPriority? priority = null)
{
if (IsMainThread)
{
action();
}
else
{
Instance.PlatformBeginInvokeOnMainThread(action, priority);
}
}
public static Task InvokeOnMainThreadAsync(Action action, DispatcherPriority? priority = null)
{
if (IsMainThread)
{
action();
#if NETSTANDARD1_0
return Task.FromResult(true);
#else
return Task.CompletedTask;
#endif
}
var tcs = new TaskCompletionSource();
BeginInvokeOnMainThread(() =>
{
try
{
action();
tcs.TrySetResult(true);
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
}, priority);
return tcs.Task;
}
public static Task InvokeOnMainThreadAsync(Func func, DispatcherPriority? priority = null)
{
if (IsMainThread)
{
return Task.FromResult(func());
}
var tcs = new TaskCompletionSource();
BeginInvokeOnMainThread(() =>
{
try
{
var result = func();
tcs.TrySetResult(result);
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
}, priority);
return tcs.Task;
}
public static Task InvokeOnMainThreadAsync(Func funcTask, DispatcherPriority? priority = null)
{
if (IsMainThread)
{
return funcTask();
}
var tcs = new TaskCompletionSource