c#若何利用多線程,簡單幾步,讓你輕松幾步解決。
1. 打開vs或者其他IDE, 建立節制臺項目如下
2. 無參數的多線程。在Program.cs文件里面寫入如下代碼
class Program
{
static void Main(string[] args)
{
int num = 2;
for ( int i =0; i < num; i++)
{
noParmaThread();
}
}
private static void StartThread()
{
Console.WriteLine("---------起頭了新線程---------");
Thread.Sleep(2000);//wait
Console.WriteLine("---------線程竣事---------");
}
//不需要傳遞參數
private static void noParmaThread()
{
ThreadStart threadStart = new ThreadStart(StartThread);
var thread = new Thread(threadStart);
thread.Start();//起頭線程
}
}
3 步調2的運行成果,如下圖
4. 含參數多線程。
static void Main(string[] args)
{
int num = 3;
for ( int i =0; i < num; i++)
{
oneParamThread("第" + i.ToString() +"個");
}
}
private static void oneParamThread( string param)
{
var thread = new Thread(new ParameterizedThreadStart(StartThread));
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start(param);
thread.Join();
}
private static void StartThread(Object obj)
{
string s = obj as string;
Console.WriteLine("---------起頭了 "+s +" 新線程---------");
Thread.Sleep(2000);//wait
Console.WriteLine("---------線程 "+s+" 竣事---------");
}
5. 步調4的運行成果如下圖所示
6. 利用專門的線程類。代碼如下
class Program
{
static void Main(string[] args)
{
int num = 3;
for ( int i =0; i < num; i++)
{
MyThreadClass mt = new MyThreadClass(i);
ThreadStart threadStart = new ThreadStart(mt.StartThread);
Thread thread = new Thread(threadStart);
thread.Start();
//期待線程竣事
}
}
}
public class MyThreadClass
{
public string output { set; get; }
public int parame { set; get; }
public MyThreadClass(int p)
{
this.parame = p;
}
public void StartThread()
{
Console.WriteLine("---------起頭了 " + parame.ToString() + " 新線程---------");
Thread.Sleep(2000);//wait
output = "線程 "+ parame+" 竣事了";
Console.WriteLine("---------線程 " + parame.ToString() + " 竣事---------");
}
}
7. 步調6的成果如下圖
若是您感覺有效,記得鄙人方點擊投票、點贊、存眷、留言,小編會按期送上更多的驚喜哦,您的撐持才是小編繼續盡力的動力,么么噠。
0 篇文章
如果覺得我的文章對您有用,請隨意打賞。你的支持將鼓勵我繼續創作!