class Program
{
public delegate void ss(string s);
public static void print(string s)
{
Console.WriteLine("asynchronous thread..."+s+DateTime.Now.ToLongTimeString());
System.Threading.Thread.Sleep(3000);
}
static void Main(string[] args)
{
ss s = print;
Console.WriteLine("Main thread..." + DateTime.Now.ToLongTimeString());
IAsyncResult result = s.BeginInvoke("hello", null, null);
for (int i = 0; i < 50; i++)
{
Console.WriteLine("Main...thread..."+DateTime.Now.ToLongTimeString());
}
System.Threading.Thread.Sleep(3000);
Console.WriteLine("Main...thread...after sleep" + DateTime.Now.ToLongTimeString());
Console.WriteLine("Main...thread...after sleep..." + DateTime.Now.ToLongTimeString());
s.EndInvoke(result);
輸出是:混淆異步編程
Main thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
**asynchronous thread...hello 4:20:01 PM**
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
Main...thread...4:20:01 PM
**Main...thread...after sleep4:20:04 PM**
**Main...thread...after sleep...4:20:04 PM**
我的問題是,爲什麼睡眠方法不會在異步方法算什麼?
究竟你你的問題的意思...嘗試在異步方法你的睡眠之後添加的輸出,這可能使事情更清楚?你......(睡眠不是跨越所有線程,只是執行包含睡眠的代碼的線程)。 – Jens
哦!感謝延斯,這兩個是在不同的線程...一個更多的問題,如果我不使用endInvoke()它會得到一些潛在的問題? –
@Darkterror_jl委託調用的結果將被緩存,直到您調用EndInvoke。所以,最好把它叫做快速釋放資源(btw文檔說你應該總是叫它) –