using System.Runtime.Versioning; namespace XFEExtension.NetCore.ThreadExtension; /// /// 线程的拓展 /// public static class ThreadExtension { #region 等待线程状态 /// extension(List threads) { /// /// 等待指定线程组的所有线程完成 /// /// 等待任务 public Task WaitThreadListComplete() { return Task.Run(() => { while (true) { var isAllThreadComplete = true; foreach (var thread in threads) { if (thread.ThreadState != ThreadState.Stopped) { isAllThreadComplete = false; break; } } if (isAllThreadComplete) { break; } } }); } /// /// 等待指定线程组的所有线程达到指定状态 /// /// 线程的状态 /// public Task WaitThreadListComplete(ThreadState threadState) { return Task.Run(() => { while (true) { var isAllThreadComplete = true; foreach (var thread in threads) { if (thread.ThreadState != threadState) { isAllThreadComplete = false; break; } } if (isAllThreadComplete) { break; } } }); } } /// extension(Thread thread) { /// /// 等待指定线程完成 /// /// 等待任务 public Task WaitThreadComplete() { return Task.Run(() => { while (thread.ThreadState != ThreadState.Stopped) ; }); } /// /// 等待指定线程达到指定状态 /// /// 线程的状态 /// public Task WaitThreadComplete(ThreadState threadState) { return Task.Run(() => { while (thread.ThreadState != threadState) ; }); } } #endregion #region 新建线程并开始 /// /// 新建一个线程并开始 /// /// 线程方法 /// 传递的参数 /// public static Thread StartNewThread(ParameterizedThreadStart method, object parameter) { Thread thread = new(method); thread.Start(parameter); return thread; } /// /// 新建一个线程并开始 /// /// 线程方法 /// public static Thread StartNewThread(ThreadStart method) { Thread thread = new(method); thread.Start(); return thread; } /// /// 新建一个线程并开始 /// /// 线程方法 /// 传递的参数 /// 线程的状态 /// [SupportedOSPlatform("windows")] public static Thread StartNewThread(ParameterizedThreadStart method, object parameter, ApartmentState apartmentState) { Thread thread = new(method); #if WINDOWS thread.SetApartmentState(apartmentState); #endif thread.Start(parameter); return thread; } /// /// 新建一个线程并开始 /// /// 线程方法 /// 线程的状态 /// [SupportedOSPlatform("windows")] public static Thread StartNewThread(ThreadStart method, ApartmentState apartmentState) { Thread thread = new(method); #if WINDOWS thread.SetApartmentState(apartmentState); #endif thread.Start(); return thread; } #endregion }