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