IAsyncResult 異步設計模式通過名為 BeginOperationName 和 EndOperationName 的兩個方法來實現原同步方法的異步調用
Begin 方法包含同步方法簽名中的任何參數
End 方法用於結束異步操作並返回結果
開始異步操作後如果要阻止應用程序
如果不阻止應用程序
代碼
C#異步編程模式IAsyncResult之IAsyncResult 接口
public interface IAsyncResult
{
object AsyncState { get; }
WaitHandle AsyncWaitHandle { get; }
bool CompletedSynchronously { get; }
bool IsCompleted { get; }
}
我用一個 AsyncDemo 類作為異步方法的提供者
public class AsyncDemo
{
// Use in asynchronous methods
private delegate string runDelegate();
private string m_Name;
private runDelegate m_Delegate;
public AsyncDemo(string name)
{
m_Name = name;
m_Delegate = new runDelegate(Run);
}
/**//// ﹤summary﹥
/// Synchronous method
/// ﹤/summary﹥
/// ﹤returns﹥﹤/returns﹥
public string Run()
{
return
}
/**//// ﹤summary﹥
/// Asynchronous begin method
/// ﹤/summary﹥
/// ﹤param name=
/// ﹤param name=
/// ﹤returns﹥﹤/returns﹥
public IAsyncResult BeginRun(
AsyncCallback callBack
{
try
{
return m_Delegate
}
catch(Exception e)
{
// Hide inside method invoking stack
throw e;
}
}
/**//// ﹤summary﹥
/// Asynchronous end method
/// ﹤/summary﹥
/// ﹤param name=
/// ﹤returns﹥﹤/returns﹥
public string EndRun(IAsyncResult ar)
{
if (ar == null)
throw new NullReferenceException(
try
{
return m_Delegate
}
catch (Exception e)
{
// Hide inside method invoking stack
throw e;
}
}
}
C#異步編程模式IAsyncResult操作步驟
class AsyncTest
{
static void Main(string[] args)
{
AsyncDemo demo = new AsyncDemo(
// Execute begin method
IAsyncResult ar = demo
// You can do other things here
// Use end method to block thread
// until the operation is complete
string demoName = demo
Console
}
}
也可以用 IAsyncResult 的 AsyncWaitHandle 屬性
class AsyncTest
{
static void Main(string[] args)
{
AsyncDemo demo = new AsyncDemo(
// Execute begin method
IAsyncResult ar = demo
// You can do other things here
// Use AsyncWaitHandle
ar
if (ar
{
// Still need use end method to get result
// but this time it will return immediately
string demoName = demo
Console
}
else
{
Console
can
}
}
}
C#異步編程模式IAsyncResult要注意的還有
class AsyncTest
{
static void Main(string[] args)
{
AsyncDemo demo = new AsyncDemo(
// Execute begin method
IAsyncResult ar = demo
Console
while (!ar
{
Console
// You can do other things here
}
Console
// Still need use end method to get result
//but this time it will return immediately
string demoName = demo
Console
}
}
最後是使用回調方法並加上狀態對象
class AsyncTest
{
static AsyncDemo demo = new AsyncDemo(
static void Main(string[] args)
{
// State object
bool state = false;
// Execute begin method
IAsyncResult ar = demo
new AsyncCallback(outPut)
// You can do other thins here
// Wait until callback finished
System
}
// Callback method
static void outPut(IAsyncResult ar)
{
bool state = (bool)ar
string demoName = demo
if (state)
{
Console
}
else
{
Console
}
}
}
C#異步編程模式IAsyncResult的後話
對於一個已經實現了 BeginOperationName 和 EndOperationName方法的對象
C#異步編程模式IAsyncResult的基本情況就向你介紹到這裡
From:http://tw.wingwit.com/Article/program/net/201311/11864.html