(1)不需要傳遞參數,也不需要回傳參數
ThreadStart是一個委託,這個委託的定義為void ThreadStart(),沒有參數與回傳值。
class Program { static void Main(string[] args) { for (int i = 0; i < 30; i++) { ThreadStart threadStart = new ThreadStart(Calculate); Thread thread = new Thread(threadStart); thread.Start(); } Thread.Sleep(2000); Console.Read(); } public static void Calculate() { DateTime time = DateTime.Now;//得到当前时间 Random ra = new Random();//随机数对象 Thread.Sleep(ra.Next(10,100));//随机休眠一段时间 Console.WriteLine(time.Minute + ":" + time.Millisecond); } }
(2)需要傳遞單一參數
ParameterThreadStart委託定義為void ParameterizedThreadStart(object state),有一個參數但沒有回傳值。
class Program { static void Main(string[] args) { for (int i = 0; i < 30; i++) { ParameterizedThreadStart tStart = new ParameterizedThreadStart(Calculate); Thread thread = new Thread(tStart); thread.Start(i*10+10);//传递参数 } Thread.Sleep(2000); Console.Read(); } public static void Calculate(object arg) { Random ra = new Random();//随机数对象 Thread.Sleep(ra.Next(10, 100));//随机休眠一段时间 Console.WriteLine(arg); } }
(3)使用專門的線程類別(常用)
使用線程類別可以有多個參數與多個返回值,十分靈活!
class Program { static void Main(string[] args) { MyThread mt = new MyThread(100); ThreadStart threadStart = new ThreadStart(mt.Calculate); Thread thread = new Thread(threadStart); thread.Start(); //等待线程结束 while (thread.ThreadState != ThreadState.Stopped) { Thread.Sleep(10); } Console.WriteLine(mt.Result);//打印返回值 Console.Read(); } } public class MyThread//线程类 { public int Parame { set; get; }//参数 public int Result { set; get; }//返回值 //构造函数 public MyThread(int parame) { this.Parame = parame; } //线程执行方法 public void Calculate() { Random ra = new Random();//随机数对象 Thread.Sleep(ra.Next(10, 100));//随机休眠一段时间 Console.WriteLine(this.Parame); this.Result = this.Parame * ra.Next(10, 100); } }
(4)使用匿名方法(常用)
使用匿名方法啟動執行緒可以有多個參數和回傳值,而且使用非常方便!
class Program { static void Main(string[] args) { int Parame = 100;//当做参数 int Result = 0;//当做返回值 //匿名方法 ThreadStart threadStart = new ThreadStart(delegate() { Random ra = new Random();//随机数对象 Thread.Sleep(ra.Next(10, 100));//随机休眠一段时间 Console.WriteLine(Parame);//输出参数 Result = Parame * ra.Next(10, 100);//计算返回值 }); Thread thread = new Thread(threadStart); thread.Start();//多线程启动匿名方法 //等待线程结束 while (thread.ThreadState != ThreadState.Stopped) { Thread.Sleep(10); } Console.WriteLine(Result);//打印返回值 Console.Read(); } }
(5)使用委託開啟多執行緒(多執行緒深入)
1、用委託(Delegate)的BeginInvoke和EndInvoke方法操作執行緒
BeginInvoke方法可以使用執行緒非同步地執行委託所指向的方法。然後透過EndInvoke方法得到方法的回傳值(EndInvoke方法的回傳值就是被呼叫方法的回傳值),或是確定方法已經被成功呼叫。
class Program { private delegate int NewTaskDelegate(int ms); private static int newTask(int ms) { Console.WriteLine("任务开始"); Thread.Sleep(ms); Random random = new Random(); int n = random.Next(10000); Console.WriteLine("任务完成"); return n; } static void Main(string[] args) { NewTaskDelegate task = newTask; IAsyncResult asyncResult = task.BeginInvoke(2000, null, null); //EndInvoke方法将被阻塞2秒 int result = task.EndInvoke(asyncResult); Console.WriteLine(result); Console.Read(); } }
2、使用IAsyncResult.IsCompleted屬性來判斷非同步呼叫是否完成
class Program { private delegate int NewTaskDelegate(int ms); private static int newTask(int ms) { Console.WriteLine("任务开始"); Thread.Sleep(ms); Random random = new Random(); int n = random.Next(10000); Console.WriteLine("任务完成"); return n; } static void Main(string[] args) { NewTaskDelegate task = newTask; IAsyncResult asyncResult = task.BeginInvoke(2000, null, null); //等待异步执行完成 while (!asyncResult.IsCompleted) { Console.Write("*"); Thread.Sleep(100); } // 由于异步调用已经完成,因此, EndInvoke会立刻返回结果 int result = task.EndInvoke(asyncResult); Console.WriteLine(result); Console.Read(); } }
3、使用WaitOne方法等待非同步方法執行完成
WaitOne的第一個參數表示要等待的毫秒數,在指定時間之內, WaitOne方法將等待,直到非同步呼叫完成,並發出通知,WaitOne方法才會傳回true。當等待指定時間之後,非同步呼叫仍未完成,WaitOne方法傳回false,如果指定時間為0,表示不等待,如果為-1,表示永遠等待,直到非同步呼叫完成。
class Program { private delegate int NewTaskDelegate(int ms); private static int newTask(int ms) { Console.WriteLine("任务开始"); Thread.Sleep(ms); Random random = new Random(); int n = random.Next(10000); Console.WriteLine("任务完成"); return n; } static void Main(string[] args) { NewTaskDelegate task = newTask; IAsyncResult asyncResult = task.BeginInvoke(2000, null, null); //等待异步执行完成 while (!asyncResult.AsyncWaitHandle.WaitOne(100, false)) { Console.Write("*"); } int result = task.EndInvoke(asyncResult); Console.WriteLine(result); Console.Read(); } }
4、使用回呼方式回傳結果
要注意的是“my.BeginInvoke(3,300, MethodCompleted, my)”,BeginInvoke方法的參數傳遞方式:
前面一部分(3,300)是其委託本身的參數。
倒數第二個參數(MethodCompleted)是回呼方法委託類型,他是回呼方法的委託,此委託沒有回傳值,有一個IAsyncResult類型的參數,當method方法執行完後,系統會自動呼叫MethodCompleted方法。
最後一個參數(my)需要向MethodCompleted方法中傳遞一些值,一般可以傳遞被呼叫方法的委託,這個值可以使用IAsyncResult.AsyncState屬性來獲得。
class Program { private delegate int MyMethod(int second, int millisecond); //线程执行方法 private static int method(int second, int millisecond) { Console.WriteLine("线程休眠" + (second * 1000 + millisecond) + "毫秒"); Thread.Sleep(second * 1000 + millisecond); Random random = new Random(); return random.Next(10000); } //回调方法 private static void MethodCompleted(IAsyncResult asyncResult) { if (asyncResult == null || asyncResult.AsyncState == null) { Console.WriteLine("回调失败!!!"); return; } int result = (asyncResult.AsyncState as MyMethod).EndInvoke(asyncResult); Console.WriteLine("任务完成,结果:" + result); } static void Main(string[] args) { MyMethod my = method; IAsyncResult asyncResult = my.BeginInvoke(3,300, MethodCompleted, my); Console.WriteLine("任务开始"); Console.Read(); } }
5、其他元件的BeginXXX和EndXXX方法
在其他的.net元件中也有類似BeginInvoke和EndInvoke的方法,如System.Net.HttpWebRequest類別的BeginGetResponse和EndGetResponse方法。其使用方法類似委託類型的BeginInvoke和EndInvoke方法,例如:
class Program { //回调函数 private static void requestCompleted(IAsyncResult asyncResult) { if (asyncResult == null || asyncResult.AsyncState==null) { Console.WriteLine("回调失败"); return; } HttpWebRequest hwr = asyncResult.AsyncState as HttpWebRequest; HttpWebResponse response = (HttpWebResponse)hwr.EndGetResponse(asyncResult); StreamReader sr = new StreamReader(response.GetResponseStream()); string str = sr.ReadToEnd(); Console.WriteLine("返回流长度:"+str.Length); } static void Main(string[] args) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.baidu.com"); //异步请求 IAsyncResult asyncResult = request.BeginGetResponse(requestCompleted, request); Console.WriteLine("任务开始"); Console.Read(); } }

要開始C#.NET開發,你需要:1.了解C#的基礎知識和.NET框架的核心概念;2.掌握變量、數據類型、控制結構、函數和類的基本概念;3.學習C#的高級特性,如LINQ和異步編程;4.熟悉常見錯誤的調試技巧和性能優化方法。通過這些步驟,你可以逐步深入C#.NET的世界,並編寫高效的應用程序。

C#和.NET的關係是密不可分的,但它們不是一回事。 C#是一門編程語言,而.NET是一個開發平台。 C#用於編寫代碼,編譯成.NET的中間語言(IL),由.NET運行時(CLR)執行。

C#.NET依然重要,因為它提供了強大的工具和庫,支持多種應用開發。 1)C#結合.NET框架,使開發高效便捷。 2)C#的類型安全和垃圾回收機制增強了其優勢。 3).NET提供跨平台運行環境和豐富的API,提升了開發靈活性。

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C#和.NET通過不斷的更新和優化,適應了新興技術的需求。 1)C#9.0和.NET5引入了記錄類型和性能優化。 2).NETCore增強了雲原生和容器化支持。 3)ASP.NETCore與現代Web技術集成。 4)ML.NET支持機器學習和人工智能。 5)異步編程和最佳實踐提升了性能。

c#.netissutableforenterprise-levelapplications withemofrosoftecosystemdueToItsStrongTyping,richlibraries,androbustperraries,androbustperformance.however,itmaynotbeidealfoross-platement forment forment forment forvepentment offependment dovelopment toveloperment toveloperment whenrawspeedsportor whenrawspeedseedpolitical politionalitable,

C#在.NET中的編程過程包括以下步驟:1)編寫C#代碼,2)編譯為中間語言(IL),3)由.NET運行時(CLR)執行。 C#在.NET中的優勢在於其現代化語法、強大的類型系統和與.NET框架的緊密集成,適用於從桌面應用到Web服務的各種開發場景。

C#是一種現代、面向對象的編程語言,由微軟開發並作為.NET框架的一部分。 1.C#支持面向對象編程(OOP),包括封裝、繼承和多態。 2.C#中的異步編程通過async和await關鍵字實現,提高應用的響應性。 3.使用LINQ可以簡潔地處理數據集合。 4.常見錯誤包括空引用異常和索引超出範圍異常,調試技巧包括使用調試器和異常處理。 5.性能優化包括使用StringBuilder和避免不必要的裝箱和拆箱。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

Dreamweaver CS6
視覺化網頁開發工具

WebStorm Mac版
好用的JavaScript開發工具

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

記事本++7.3.1
好用且免費的程式碼編輯器