此示例演示使用線程回調方法
using System;
using System.Threading;
using System.Runtime.Remoting.Messaging;
namespace 回調
{
//委托聲明(函數簽名)
delegate string MyMethodDelegate();
class MyClass
{
//調用的方法
public static string MyMethod()
{
//Console.WriteLine(System.Threading.Thread.CurrentThread.IsBackground);
for(int i = 0;i < 3; i++) //延長時間(模擬實際任務)
{
Thread.Sleep(1000);
}
return "Hello Word";
}
//聲明委托,調用MyMethod
private static MyMethodDelegate d = new MyMethodDelegate(MyClass.MyMethod);
//聲明委托,調用AsyncCallbackMethod
private static System.AsyncCallback a = new System.AsyncCallback(MyClass.AsyncCallbackMethod);
[STAThread]
static void Main(string[] args)
{
d.BeginInvoke(a,null);
Console.ReadLine(); //這句不能去掉,否則主線程執行完成后,子線會會強迫調用Abort()方法銷毀掉,也就執行不到回調方法了
}
public static void AsyncCallbackMethod(System.IAsyncResult myIAsyncResult)
{
string strEnd = d.EndInvoke(myIAsyncResult); //委托調用的方法已經完成,輸出其值
Console.WriteLine(strEnd);
Console.Read();
}
}
}
本示例代碼已經測試,能夠正常運行!
新聞熱點
疑難解答