如果需要查看更多文章,請微信搜索公眾號 csharp編程大全,需要進C#交流群群請加微信z438679770,備注進群, 我邀請你進群! ! !
1.異步委托開啟執行緒
public class Program
{
public static void Main(string[] args)
{
Action<int, int> a = add;
a.BeginInvoke(3, 4, null, null);
Console.WriteLine("執行執行緒");
Console.ReadKey();
}
static void add(int a, int b)
{
Console.WriteLine(a + b);
}
}
2.通過Thread類開啟執行緒
public class Program
{
public static void Main(string[] args)
{
Thread t1;
Thread t2;
t1 = new Thread(SetInfo1);
t2 = new Thread(SetInfo2);
t1.Start();
//執行緒睡眠
//t1.Join(1000);
//掛起執行緒
t1.Suspend();
//繼續執行執行緒
t1.Resume();
//結束執行緒
//t1.Abort();
t2.Start();
Console.ReadKey();
}
//奇數執行緒
public static void SetInfo1()
{
for (int i = 0; i < 100; i++)
{
if (i % 2 != 0)
{
Console.WriteLine("奇數為" + i);
}
}
}
//偶數執行緒
public static void SetInfo2()
{
for (int i = 0; i < 100; i++)
{
if (i % 2 == 0)
{
Console.WriteLine("偶數為" + i);
}
}
}
}
3.通過執行緒池開啟執行緒
//執行緒池可以看做容納執行緒的容器;一個應用程式最多只能有一個執行緒池;ThreadPool靜態類通過QueueUserWorkItem()方法將作業函式排入執行緒池;每排入一個作業函式,就相當于請求創建一個執行緒;
//執行緒池的作用:
//1、執行緒池是為突然大量爆發的執行緒設計的,通過有限的幾個固定執行緒為大量的操作服務,減少了創建和銷毀執行緒所需的時間,從而提高效率,
//2、如果一個執行緒的時間非常長,就沒必要用執行緒池了(不是不能作長時間操作,而是不宜,),況且我們還不能控制執行緒池中執行緒的開始、掛起、和中止
public class Program
{
public static void Main(string[] args)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(TestThreadPool), new string[] { "hjh" });
Console.ReadKey();
}
public static void TestThreadPool(object state)
{
string[] arry = state as string[];//傳過來的引數值
int workerThreads = 0;
int CompletionPortThreads = 0;
ThreadPool.GetMaxThreads(out workerThreads, out CompletionPortThreads);
Console.WriteLine(DateTime.Now.ToString() + "---" + arry[0] + "--workerThreads=" + workerThreads + "--CompletionPortThreads" + CompletionPortThreads);
}
}
4.通過任務Task開啟執行緒
public class Program
{
public static void Main(string[] args)
{
Task task = new Task(DownLoadFile_My);
task.Start();
Console.ReadKey();
}
static void DownLoadFile_My()
{
Console.WriteLine("開始下載...執行緒ID:"+Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(500);
Console.WriteLine("下載完成!");
}
}
如果需要查看更多文章,請微信搜索公眾號 csharp編程大全,需要進C#交流群群請加微信z438679770,備注進群, 我邀請你進群! ! !
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/168972.html
標籤:.NET技术
