程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> c#應用多線程的幾種方法示例詳解

c#應用多線程的幾種方法示例詳解

編輯:C#入門知識

c#應用多線程的幾種方法示例詳解。本站提示廣大學習愛好者:(c#應用多線程的幾種方法示例詳解)文章只能為提供參考,不一定能成為您想要的結果。以下是c#應用多線程的幾種方法示例詳解正文


(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.百度.com");

//異步要求

IAsyncResult asyncResult = request.BeginGetResponse(requestCompleted, request);

Console.WriteLine("義務開端");

Console.Read();

}

}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved