1.异步委托开启线程
注意: 1.若使用异步委托开启线程,则委托仅允许添加一个方法; 2.启用委托开启线程,可以多次启用线程,相当于再次启用另一条线程;
public static Action<string, int> Test;
public static void StartThread(string name, int num)
{
Test = Add;
Test?.BeginInvoke(name, num, null, null);
}
private static void Add(string name, int num)
{
for (int i = 0; i < 10; i++)
{
Debug.WriteLine($"{name}:{num + i}");
Thread.Sleep(100);
}
}
2.通过线程池开启线程
public static void ThreadTest()
{
ThreadPool.QueueUserWorkItem(TestThreadPool, new[] { "hjh" });
int workerThreads;
int completionPortThreads;
ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads);
Debug.WriteLine("线程池中辅助线程的最大数目=" + workerThreads);
Debug.WriteLine("线程池中异步 I / O 线程的最大数目" + completionPortThreads);
}
public static void TestThreadPool(object state)
{
Thread.Sleep(3000);
string[] arry = state as string[];
Debug.WriteLine(DateTime.Now + "---" + arry[0]);
}
3.通过Task任务开启线程
public static void Thread_4()
{
new Task(() => { Test(10); }).Start();
new Task(() => { Test(10); }).Start();
}
private static void Test(int num)
{
Console.WriteLine($"线程ID:{Thread.CurrentThread.ManagedThreadId},开始执行");
long result = SumNumbers(num);
Console.WriteLine($"线程执行结果:{result}");
}
static long SumNumbers(int count)
{
long sum = 0;
for (int i = 0; i < count; i++)
{
sum += i;
}
Thread.Sleep(500);
return sum;
}
Task类开启线程: Thread类开启线程:
|