XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Runtime.InteropServices;

namespace XFEToolBox.Client.Core.Search;

/// <summary>Runs synchronous indexing work away from both the UI and the shared thread pool.</summary>
internal static class FileIndexWorker
{
    public static Task Run(Action action, string name, CancellationToken token, bool backgroundIo = false)
    {
        var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
        var thread = new Thread(() =>
        {
            // This mode is thread-affine. Never enter it in an async/thread-pool callback.
            // Only IO producers use it; the consumer holding the search index lock does not.
            var background = backgroundIo && OperatingSystem.IsWindows() &&
                SetThreadPriority(GetCurrentThread(), 0x00010000);
            try
            {
                token.ThrowIfCancellationRequested();
                action();
                completion.TrySetResult();
            }
            catch (OperationCanceledException) when (token.IsCancellationRequested) { completion.TrySetCanceled(token); }
            catch (Exception error) { completion.TrySetException(error); }
            finally
            {
                if (background) SetThreadPriority(GetCurrentThread(), 0x00020000);
            }
        }) { IsBackground = true, Name = name, Priority = ThreadPriority.BelowNormal };
        thread.Start();
        return completion.Task;
    }

    internal static void Wait(ValueTask task)
    {
        if (task.IsCompletedSuccessfully) task.GetAwaiter().GetResult();
        else task.AsTask().GetAwaiter().GetResult();
    }

    internal static T Wait<T>(ValueTask<T> task) => task.IsCompletedSuccessfully
        ? task.Result : task.AsTask().GetAwaiter().GetResult();

    [DllImport("kernel32.dll")]
    private static extern IntPtr GetCurrentThread();
    [DllImport("kernel32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool SetThreadPriority(IntPtr thread, int priority);
}