2016-09-17 46 views
0

我想了解C#,並且很困惑這段代碼。C#這是什麼=>語法意思是

Thread thread = new Thread(new ThreadStart(() => 
{ 
     Thread.Sleep(_rnd.Next(50, 200)); 
     //do other stuff 
})); 
thread.Start(); 

我知道一個線程正在創建,然後啓動,但我不明白在這種情況下=>語法。從檢查這個網站上的其他帖子,很難找到關於=>的信息,我認爲這是與代表有關,或者是有什麼東西被退回?任何人都可以對此有所瞭解嗎?謝謝。

+1

這是'委託'簡寫語法 – Typist

回答

1

下面你會發現一些不同的方式來處理函數和委託。全部做同樣的事情:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading; 
using System.Threading.Tasks; 

namespace SO39543690 
{ 
    class Program 
    { 
    static Random _rnd = new Random(); 

    static void Proc() 
    { 
     Console.WriteLine("3. Processing..."); 
     Thread.Sleep(_rnd.Next(50, 200)); 
    } 

    static void Main(string[] args) 
    { 
     Thread thread = new Thread(new ThreadStart(() => 
     { 
     Console.WriteLine("1. Processing..."); 
     Thread.Sleep(_rnd.Next(50, 200)); 
     })); 
     thread.Start(); 

     thread = new Thread(() => 
     { 
     Console.WriteLine("2. Processing..."); 
     Thread.Sleep(_rnd.Next(50, 200)); 
     }); 
     thread.Start(); 

     thread = new Thread(Proc); 
     thread.Start(); 

     thread = new Thread(delegate() 
     { 
     Console.WriteLine("4. Processing..."); 
     Thread.Sleep(_rnd.Next(50, 200)); 
     }); 
     thread.Start(); 

     Action proc =() => 
     { 
     Console.WriteLine("5. Processing..."); 
     Thread.Sleep(_rnd.Next(50, 200)); 
     }; 
     thread = new Thread(new ThreadStart(proc)); 
     thread.Start(); 


     Console.WriteLine("END"); 
     Console.ReadLine(); 
    } 
    } 
}