最近,在看C#進階編程第七版的線程、任務、同步這一章,因為現在多線程編程,非同步編程對構建響應靈敏的介面以及構建高延展性的服務應用是多麼重要。現在就來記錄一下自己今天學習的成果。
建立線程的一種簡單方式是定義一個委託,並非同步呼叫它。總結一下,非同步呼叫委託的方式有如下3種:
1.投票
//定義一個需要一定的時間才能執行完畢的方法
static int TakesAWhile(int data, int ms)
{
Console.WriteLine("TakesAWhile started");
Thread.Sleep(ms);
Console.WriteLine("TakesAWhile completed");
return ++data;
}
//要從委託中調用這個方法,必須定義一個有相同參數和傳回型別的委託
public delegate int TakesAWhileDelegate(int data,int ms);
//所建立的delegate類提供了BeginInvoke()方法,在該方法中,可以傳遞用委託定義的輸入的函數。BeginInvoke()方法總是有AsyncCallback和object類型的兩個額外參數。BeginInvoke()方法的傳回型別是IAsyncResult。通過IAsyncResult,可以獲得該委託的相關資訊,並通過IsCompleted屬性驗證該委託是否完成了任務。只要委託沒有完成其任務,程式的主線程就繼續執行while迴圈。
static void Main(string[] args)
{
TakesAWhileDelegate d1 = TakesAWhile;
//使用投票方式調用非同步委託
IAsyncResult ar = d1.BeginInvoke(1, 3000, null, null);
while (!ar.IsCompleted)
{
//doing something else in the main thread
Console.Write(".");
Thread.Sleep(50);
}
int result = d1.EndInvoke(ar);
Console.WriteLine("result:{0}", result);
}
2.等待控制代碼
static void Main(string[] args)
{
TakesAWhileDelegate d1 = TakesAWhile;
//使用等待控制代碼的方式調用非同步委託
while (true)
{
Console.Write(".");
if (ar.AsyncWaitHandle.WaitOne(50, false))
{
Console.WriteLine("Can get the result now");
break;
}
int result = d1.EndInvoke(ar);
Console.WriteLine("result:{0}", result);
}
}
3.使用非同步回調
static void Main(string[] args)
{
TakesAWhileDelegate d1 = TakesAWhile;
d1.BeginInvoke(1, 3000, TakesAWhileCompleted, d1);
for (int i = 0; i < 100; i++)
{
Console.Write(".");
Thread.Sleep(50);
}
}
static void TakesAWhileCompleted(IAsyncResult ar)
{
if (ar == null) throw new ArgumentException("ar");
TakesAWhileDelegate d1 = ar.AsyncState as TakesAWhileDelegate;
Trace.Assert(d1 != null, "Invalid object type");
int result = d1.EndInvoke(ar);
Console.WriteLine("result:{0}", result);
}
//使用非同步回調-lamda運算式的方式調用委託
static void Main(string[] args)
{
d1.BeginInvoke(1, 3000, ar =>
{
int result = d1.EndInvoke(ar);
Console.WriteLine("result:{0}", result);
}, null);
for (int i = 0; i < 100; i++)
{
Console.Write(".");
Thread.Sleep(50);
}
}