public interface IAsyncResult
{
object AsyncState { get; }
WaitHandle AsyncWaitHandle { get; }
bool CompletedSynchronously { get; }
bool IsCompleted { get; }
}
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);
}
/**////
/// Synchronous method
///
///
public string Run()
{
return "My name is " + m_Name;
}
/**////
/// Asynchronous begin method
///
///
///
///
public IAsyncResult BeginRun(AsyncCallback callBack, Object stateObject)
{
try
{
return m_Delegate.BeginInvoke(callBack, stateObject);
}
catch(Exception e)
{
// Hide inside method invoking stack
throw e;
}
}
/**////
/// Asynchronous end method
///
///
///
public string EndRun(IAsyncResult ar)
{
if (ar == null)
throw new NullReferenceException("Arggument ar can't be null");
try
{
return m_Delegate.EndInvoke(ar);
}
catch (Exception e)
{
// Hide inside method invoking stack
throw e;
}
}
}
class AsyncTest
{
static void Main(string[] args)
{
AsyncDemo demo = new AsyncDemo("jiangnii");
// Execute begin method
IAsyncResult ar = demo.BeginRun(null, null);
// You can do other things here
// Use end method to block thread until the operation is complete
string demoName = demo.EndRun(ar);
Console.WriteLine(demoName);
}
}
class AsyncTest
{
static void Main(string[] args)
{
AsyncDemo demo = new AsyncDemo("jiangnii");
// Execute begin method
IAsyncResult ar = demo.BeginRun(null, null);
// You can do other things here
// Use AsyncWaitHandle.WaitOne method to block thread for 1 second at most
ar.AsyncWaitHandle.WaitOne(1000, false);
if (ar.IsCompleted)
{
// Still need use end method to get result, but this time it will return immediately
string demoName = demo.EndRun(ar);
Console.WriteLine(demoName);
}
else
{
Console.WriteLine("Sorry, can't get demoName, the time is over");
}
}
}
class AsyncTest
{
static void Main(string[] args)
{
AsyncDemo demo = new AsyncDemo("jiangnii");
// Execute begin method
IAsyncResult ar = demo.BeginRun(null, null);
Console.Write("Waiting..");
while (!ar.IsCompleted)
{
Console.Write(".");
// You can do other things here
}
Console.WriteLine();
// Still need use end method to get result, but this time it will return immediately
string demoName = demo.EndRun(ar);
Console.WriteLine(demoName);
}
}
class AsyncTest
{
static AsyncDemo demo = new AsyncDemo("jiangnii");
static void Main(string[] args)
{
// State object
bool state = false;
// Execute begin method
IAsyncResult ar = demo.BeginRun(new AsyncCallback(outPut), state);
// You can do other thins here
// Wait until callback finished
System.Threading.Thread.Sleep(1000);
}
// Callback method
static void outPut(IAsyncResult ar)
{
bool state = (bool)ar.AsyncState;
string demoName = demo.EndRun(ar);
if (state)
{
Console.WriteLine(demoName);
}
else
{
Console.WriteLine(demoName + ", isn't it?");
}
}
}
【责任编辑: lanier】