使用委託非同步呼叫方法讓程式並行執行

2021-09-08 08:42:25 字數 1480 閱讀 9451

通常情況下,如果需要非同步執行乙個耗時的操作,我們會新起乙個執行緒,然後讓這個執行緒去執行**。但是對於每乙個非同步呼叫都通過建立執行緒來進行操作顯然會對效能產生一定的影響,同時操作也相對繁瑣一些。.net 中可以通過委託進行方法的非同步呼叫,就是說客戶端在非同步呼叫方法時,本身並不會因為方法的呼叫而中斷,而是從執行緒池中抓取乙個執行緒去執行該方法,自身執行緒(主線程)在完成抓取執行緒這一過程之後,繼續執行下面的**,這樣就實現了**的並行執行使用執行緒池的好處就是避免了頻繁進行非同步呼叫時建立、銷毀執行緒的開銷

當我們在委託物件上呼叫begininvoke()時,便進行了乙個非同步的方法呼叫。呼叫 endinvoke() 時就可以獲得委託的返回值。

using system.collections.generic;
using system.linq;
using system.text;
using system.io;
using system.runtime.serialization.formatters.binary;
using system.xml;
using system.threading;
: client executed  second(s).", thread.currentthread.name, i);
}
// 傳遞 iasyncresult 物件
int rtnval = del.endinvoke(asyncresult);
console.writeline("result: \n", rtnval);
console.writeline("\npress any key to exit...");
console.readline();
}
public

delegate

int adddelegate(int a, int b);

public

class cal

console.writeline("method invoked!");
// 做某些其它的事情,模擬需要執行 2 秒鐘
for (int i = 0; i < 2; i++)
: add executed  second(s).", thread.currentthread.name, i);
}
console.writeline("method complete!");
return a + b;
}
}
}
}

C 委託非同步呼叫

廢話不多說,直接上 ps 我就喜歡簡單 直接 粗暴 using system using system.collections.generic using system.linq using system.runtime.remoting.messaging using system.text us...

執行緒 委託的非同步呼叫

c programming p323 begininvoke 會立即返回,它將建立乙個另乙個執行緒來完成自己的工作。當我需要它執行後的結果時 例如 pubilc delegate in testdetegate pubilc testdetegate thedetegate thedetegate ...

C 委託的非同步呼叫

本文將主要通過 同步呼叫 非同步呼叫 非同步 三個示例來講解在用委託執行同乙個 加法類 的時候的的區別和利弊。首先,通過 定義乙個委託和下面三個示例將要呼叫的方法 新增的命名空間 using system.threading using system.runtime.remoting.messagi...