C#使用委托的形式調(diào)用線程代碼實例
更新時間:2018年10月26日 08:59:31 作者:Czhenya
今天小編就為大家分享一篇關(guān)于C#使用委托的形式調(diào)用線程代碼實例,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
委托
對于委托,我們都知道他是一個引用類型,具有引用類型所具有的通性。需要知道的是它保存的不是實際值,只是是保存對存儲在托管堆中的對象的引用?;蛘f的直接點,委托就相當于叫人幫忙,讓你幫你做一些事情。我這里就使用委托的形式,調(diào)用線程,來簡單的說一下。
代碼如下:
using System;
using System.Threading;
namespace _012_線程
{
class Program
{
static void Main(string[] args) //在mian中線程是執(zhí)行一個線程里面的語句的執(zhí)行,是從上到下的
{
//通過委托 開啟一個線程
//==============可用泛型傳參數(shù)(無返回值)==============
Action threaA = ThreadTestA;
threaA.BeginInvoke(null,null); //開啟一個新的線程去執(zhí)行,threaA所引用的方法
Action<int> threaB = ThreadTestB;
threaB.BeginInvoke(111,null, null);
//可以認為線程是同時執(zhí)行的 (異步執(zhí)行)
Console.WriteLine("異步執(zhí)行");
//================帶返回值的形式====================
//第一種方式 檢測線程結(jié)束 ----- IsCompleted線程是否行完畢
//Func<int, int> threaC = ThreadTestC;
////接收異步線程返回值
//IAsyncResult returnResult = threaC.BeginInvoke(111, null, null);
//while (!res.IsCompleted)
//{
// Console.Write(".");
// Thread.Sleep(10); //控制子線程的檢測頻率,(每10ms檢測一次)
//}
////取得異步線程返回值
//int result = threaC.EndInvoke(res);
//Console.WriteLine("IsCompleted方式檢測:" + result);
//第二種方式 檢測線程結(jié)束 ----- 1000ms沒結(jié)束就返回false,反之
Func<int, int> threaC = ThreadTestC;
//接收異步線程返回值
IAsyncResult returnResult = threaC.BeginInvoke(111, null, null);
bool isEnd = returnResult.AsyncWaitHandle.WaitOne(1000);
int result = 0;
if (isEnd)
{
result = threaC.EndInvoke(returnResult);
}
Console.WriteLine("EndInvoke()方式檢測:" + isEnd +" "+ result);
//第三種方式 檢測線程結(jié)束 ----- 通過回調(diào),檢測線程結(jié)束
Func<int,string, string> threaD = ThreadTestD;
//倒數(shù)第二個參數(shù),表示委托類型的參數(shù),(回調(diào)函數(shù))當線程結(jié)束的時候會調(diào)用這個委托指向的方法
//最后一個參數(shù),用來給回調(diào)函數(shù)傳遞數(shù)據(jù)
IAsyncResult asy = threaD.BeginInvoke(111,"Czhenya", OnCallKey, threaD);
//改為Lamdba表達式
threaD.BeginInvoke(111, "Czhenya",(ar)=>{
string res = threaD.EndInvoke(ar);
Console.WriteLine("在Lamdba表達式中取得:"+res);
},null);
Console.ReadKey();
}
static void OnCallKey(IAsyncResult ar)
{
Func<int, string, string> thread = ar.AsyncState as Func<int, string, string>;
string res = thread.EndInvoke(ar);
Console.WriteLine("在回調(diào)函數(shù)中取到的結(jié)果 :"+res);
}
/// <summary>
/// 一般是比較耗時的操作方法
/// </summary>
static void ThreadTestA()
{
Console.WriteLine("ThreaTestA");
}
static void ThreadTestB(int num)
{
Console.WriteLine("ThreaTestB "+num);
}
static int ThreadTestC(int num)
{
Console.WriteLine("ThreaTestC");
Thread.Sleep(100); //讓當前線程休眠(暫停線程(參數(shù)單位:ms))
return num;
}
static string ThreadTestD(int num,string str)
{
Console.WriteLine("ThreaTestD");
return num +" "+ str;
}
}
}
運行結(jié)果圖:

總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章
使用C#發(fā)送Http請求實現(xiàn)模擬登陸實例
本文主要介紹了使用C#發(fā)送Http請求實現(xiàn)模擬登陸實例,模擬登陸的原理簡單,想要了解的朋友可以了解一下。2016-10-10
解決WPF附加屬性的Set函數(shù)不調(diào)用的問題
這篇文章介紹了解決WPF附加屬性的Set函數(shù)不調(diào)用的方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06

