如何异步调用 visual c# 方法
2008-05-24 10:12
489 查看
using System;
using System.Threading ;
using System.Windows.Forms ;
namespace AsyncDemo
......{
/**//**//**//// <summary>
/// 如何异步调用 Visual C# 方法
/// 出自:http://support.microsoft.com/default.aspx?scid=kb%3Bzh-cn%3B315582
/// </summary>
class AsyncDemo
......{
/**//**//**//// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
......{
AsyncDemo ad = new AsyncDemo () ;
//ad.DemoSyncCall() ;
//ad.DemoEndInvoke();
//ad.DemoWaitHandle();
//ad.DemoPolling();
ad.DemoCallback();
Console.Read();
}
string LongRunningMethod (int iCallTime, out int iExecThread)
......{
Thread.Sleep (iCallTime) ;
iExecThread = AppDomain.GetCurrentThreadId ();
return "MyCallTime was " + iCallTime.ToString() ;
}
delegate string MethodDelegate(int iCallTime, out int iExecThread) ;
示例 1: 同步调用方法示例 1: 同步调用方法#region 示例 1: 同步调用方法
/**//**//**//*
* 同步调用方法
* */
/**//**//**//// <summary>
/// 示例 1: 同步调用方法
/// </summary>
public void DemoSyncCall()
......{
string s ;
int iExecThread;
// Create an instance of a delegate that wraps LongRunningMethod.
MethodDelegate dlgt = new MethodDelegate (this.LongRunningMethod) ;
// Call LongRunningMethod using the delegate.
s = dlgt(3000, out iExecThread);
Console.WriteLine(string.Format ("The delegate call returned the string: "...{0}", and the thread ID {1}", s, iExecThread.ToString() ) );
}
#endregion
示例 2: 通过 EndInvoke() 调用模式异步调用方法示例 2: 通过 EndInvoke() 调用模式异步调用方法#region 示例 2: 通过 EndInvoke() 调用模式异步调用方法
/**//**//**//*
* 使用调用模式是要调用 BeginInvoke , 做某些处理主线程, 并调用 EndInvoke() 。
* 注意不 EndInvoke() 不返回直到异步调用已完成。
* 此调用模式是有用当要有调用线程正在执行异步调用, 同时工作。
* 有同时发生工作可改善许多应用程序的性能。
* 常见任务以异步运行以此方式是文件或网络操作。
* */
/**//**//**//// <summary>
/// 示例 2: 通过 EndInvoke() 调用模式异步调用方法
/// </summary>
public void DemoEndInvoke()
......{
MethodDelegate dlgt = new MethodDelegate (this.LongRunningMethod) ;
string s ;
int iExecThread;
// Initiate the asynchronous call.
IAsyncResult ar = dlgt.BeginInvoke(1, out iExecThread, null, null);
// Do some useful work here. This would be work you want to have
// run at the same time as the asynchronous call.
// Retrieve the results of the asynchronous call.
s = dlgt.EndInvoke (out iExecThread, ar) ;
Console.WriteLine(string.Format ("The delegate call returned the string: "...{0}", and the number {1}", s, iExecThread.ToString() ) );
}
#endregion
示例 3: 异步调用方法并使用 A WaitHandle 来等待调用完成示例 3: 异步调用方法并使用 A WaitHandle 来等待调用完成#region 示例 3: 异步调用方法并使用 A WaitHandle 来等待调用完成
/**//**//**//*
* 由 BeginInvoke() 返回 IAsyncResult 具有一个 AsyncWaitHandle 属性。
* 该属性返回 WaitHandle 异步调用完成后, 通知是。 等待 WaitHandle 是常见线程同步技术。
* 通过是 WaitHandle WaitOne() 方法调用线程等待 WaitHandle 上。
* 直到是通知 WaitHandle WaitOne() 块。 当 WaitOne() 返回, 您在调用 EndInvoke() 之前进行一些额外工作。
* 对于执行文件或网络操作, 否则会阻塞调用主线程存为, 以前示例中此技术很有用。
* */
/**//**//**//// <summary>
/// 示例 3: 异步调用方法并使用 A WaitHandle 来等待调用完成
/// </summary>
public void DemoWaitHandle ()
......{
string s ;
int iExecThread;
MethodDelegate dlgt = new MethodDelegate (this.LongRunningMethod) ;
// Initiate the asynchronous call.
IAsyncResult ar = dlgt.BeginInvoke(3000, out iExecThread, null, null);
// Do some useful work here. This would be work you want to have
// run at the same time as the asynchronous call.
// Wait for the WaitHandle to become signaled.
ar.AsyncWaitHandle.WaitOne() ;
// Get the results of the asynchronous call.
s = dlgt.EndInvoke (out iExecThread, ar) ;
Console.WriteLine(string.Format ("The delegate call returned the string: "...{0}", and the number {1}", s, iExecThread.ToString() ) );
}
#endregion
示例 4: 异步调用方法通过轮询调用模式示例 4: 异步调用方法通过轮询调用模式#region 示例 4: 异步调用方法通过轮询调用模式
/**//**//**//*
* 由 BeginInvoke() 返回 IAsyncResult 对象有个 IsCompleted 属性异步调用完成后返回 True 。
* 然后可调用 EndInvoke() 。 如果您应用程序不断工作对不做要长期函数调用已被此调用模式很有用。
* MicrosoftWindows 应用程序是这样的示例。
* 主线程的 Windows 应用程序可以继续以执行异步调用时处理用户输入。
* 它可定期检查 IsCompleted 到调用是否完成。 它调用 EndInvoke 当 IsCompleted 返回 True 。
* 直到它知道操作已完成因为 EndInvoke() 阻止直到异步操作为完整, 应用程序不调用它。
* */
/**//**//**//// <summary>
/// 示例 4: 异步调用方法通过轮询调用模式
/// </summary>
public void DemoPolling()
......{
MethodDelegate dlgt = new MethodDelegate (this.LongRunningMethod) ;
string s ;
int iExecThread;
// Initiate the asynchronous call.
IAsyncResult ar = dlgt.BeginInvoke(3000, out iExecThread, null, null);
// Poll IAsyncResult.IsCompleted
while(ar.IsCompleted == false)
......{
Thread.Sleep (10) ; // pretend to so some useful work
}
s = dlgt.EndInvoke (out iExecThread, ar) ;
Console.WriteLine(string.Format ("The delegate call returned the string: "...{0}", and the number {1}", s, iExecThread.ToString() ) );
}
#endregion
示例 5: 异步方法完成后执行回调示例 5: 异步方法完成后执行回调#region 示例 5: 异步方法完成后执行回调
/**//**//**//*
* 本节, 中示例提供对 BeginInvoke() 函数, 异步调用完成后系统执行回调委托。
* 回调调用 EndInvoke() 并处理异步调用的结果。
* 如果启动异步调用线程不需要处理结果是调用此调用模式很有用。
* 异步调用完成后系统调用线程以外启动线程上调。
* 若使用此调用模式, 作为第二到最后 - BeginInvoke() 函数的参数必须传递 AsyncCallback 类型的委托。
* BeginInvoke() 还有最后参数键入 对象 到您可以将任何对象。 当它调用该对象可用于您回调函数。
* 为此参数一个重要用途是以传递用于初始化调用该委托。
* 回调函数然后使用与该委托 EndInvoke() 函数来完成调用。 此调用模式是所示。
* */
/**//**//**//// <summary>
/// 示例 5: 异步方法完成后执行回调
/// </summary>
public void DemoCallback()
......{
MethodDelegate dlgt = new MethodDelegate (this.LongRunningMethod) ;
string s ;
int iExecThread;
// Create the callback delegate.
AsyncCallback cb = new AsyncCallback(MyAsyncCallback);
// Initiate the Asynchronous call passing in the callback delegate
// and the delegate object used to initiate the call.
IAsyncResult ar = dlgt.BeginInvoke(3000, out iExecThread, cb,dlgt);
}
public void MyAsyncCallback(IAsyncResult ar)
......{
string s ;
int iExecThread ;
// Because you passed your original delegate in the asyncState parameter
// of the Begin call, you can get it back here to complete the call.
MethodDelegate dlgt = (MethodDelegate) ar.AsyncState;
// Complete the call.
s = dlgt.EndInvoke (out iExecThread, ar) ;
Console.WriteLine(string.Format ("The delegate call returned the string: "...{0}", and the number {1}", s, iExecThread.ToString() ) );
}
#endregion
}
}
using System;
using System.Threading;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Remoting.Messaging;
namespace test
{
[Serializable]
public class AsyncDemo
{
public delegate void TestRaiseEventHandler(object sender, EventArgs e);
public event TestRaiseEventHandler TestRaise;
protected virtual void OnTestRaiseEventHandler()
{
if (TestRaise != null)
{
TestRaise(this, null);
}
}
// 将被异步调用的方法
//
public string TestMethod(int callDuration, out int threadId)
{
Console.WriteLine("Test method begins.");
OnTestRaiseEventHandler();
Thread.Sleep(callDuration);
threadId = AppDomain.GetCurrentThreadId();
return "MyCallTime was " + callDuration.ToString();
}
// 序列化操作
public void Serialize(string filename)
{
Serialize(filename, this);
}
public static void Serialize(string filename, AsyncDemo async)
{
FileStream fs = new FileStream(filename, FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, async);
}
finally
{
fs.Close();
}
}
}
// 用来执行异步调用的代理
public delegate string AsyncDelegate(int callDuration, out int threadId);
public class AsyncMain
{
private static int threadId;
static void Main(string[] args)
{
// 创建测试类
AsyncDemo ad = new AsyncDemo();
// 添加事件
.(1)
ad.TestRaise += new test.AsyncDemo.TestRaiseEventHandler((new AsyncMain()).ad_TestRaise);
// 创建异步方法的代理
AsyncDelegate dlgt = new AsyncDelegate(ad.TestMethod);
// 开始执行异步调用
IAsyncResult ar = dlgt.BeginInvoke(1000,
out threadId,
new AsyncCallback(CallbackMethod),
ad );
// 等待调用完成
Console.WriteLine("Press Enter to close application.");
Console.ReadLine();
}
// 事件响应函数
void ad_TestRaise(object sender, EventArgs e)
{
Console.WriteLine("delegate call");
}
// 异步调用完成时的回调函数
static void CallbackMethod(IAsyncResult ar)
{
// 得到异步方法的代理
AsyncDelegate dlgt = (AsyncDelegate) (ar as AsyncResult).AsyncDelegate;
Console.WriteLine("begin EndInvoke");
string ret = dlgt.EndInvoke(out threadId, ar);
Console.WriteLine("The call executed on thread {0}, with return value /"
{1}/".", threadId, ret);
// 执行序列化操作
(2)
AsyncDemo demo = ar.AsyncState as AsyncDemo;
demo.Serialize("Test.dat");
}
}
}
using System.Threading ;
using System.Windows.Forms ;
namespace AsyncDemo
......{
/**//**//**//// <summary>
/// 如何异步调用 Visual C# 方法
/// 出自:http://support.microsoft.com/default.aspx?scid=kb%3Bzh-cn%3B315582
/// </summary>
class AsyncDemo
......{
/**//**//**//// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
......{
AsyncDemo ad = new AsyncDemo () ;
//ad.DemoSyncCall() ;
//ad.DemoEndInvoke();
//ad.DemoWaitHandle();
//ad.DemoPolling();
ad.DemoCallback();
Console.Read();
}
string LongRunningMethod (int iCallTime, out int iExecThread)
......{
Thread.Sleep (iCallTime) ;
iExecThread = AppDomain.GetCurrentThreadId ();
return "MyCallTime was " + iCallTime.ToString() ;
}
delegate string MethodDelegate(int iCallTime, out int iExecThread) ;
示例 1: 同步调用方法示例 1: 同步调用方法#region 示例 1: 同步调用方法
/**//**//**//*
* 同步调用方法
* */
/**//**//**//// <summary>
/// 示例 1: 同步调用方法
/// </summary>
public void DemoSyncCall()
......{
string s ;
int iExecThread;
// Create an instance of a delegate that wraps LongRunningMethod.
MethodDelegate dlgt = new MethodDelegate (this.LongRunningMethod) ;
// Call LongRunningMethod using the delegate.
s = dlgt(3000, out iExecThread);
Console.WriteLine(string.Format ("The delegate call returned the string: "...{0}", and the thread ID {1}", s, iExecThread.ToString() ) );
}
#endregion
示例 2: 通过 EndInvoke() 调用模式异步调用方法示例 2: 通过 EndInvoke() 调用模式异步调用方法#region 示例 2: 通过 EndInvoke() 调用模式异步调用方法
/**//**//**//*
* 使用调用模式是要调用 BeginInvoke , 做某些处理主线程, 并调用 EndInvoke() 。
* 注意不 EndInvoke() 不返回直到异步调用已完成。
* 此调用模式是有用当要有调用线程正在执行异步调用, 同时工作。
* 有同时发生工作可改善许多应用程序的性能。
* 常见任务以异步运行以此方式是文件或网络操作。
* */
/**//**//**//// <summary>
/// 示例 2: 通过 EndInvoke() 调用模式异步调用方法
/// </summary>
public void DemoEndInvoke()
......{
MethodDelegate dlgt = new MethodDelegate (this.LongRunningMethod) ;
string s ;
int iExecThread;
// Initiate the asynchronous call.
IAsyncResult ar = dlgt.BeginInvoke(1, out iExecThread, null, null);
// Do some useful work here. This would be work you want to have
// run at the same time as the asynchronous call.
// Retrieve the results of the asynchronous call.
s = dlgt.EndInvoke (out iExecThread, ar) ;
Console.WriteLine(string.Format ("The delegate call returned the string: "...{0}", and the number {1}", s, iExecThread.ToString() ) );
}
#endregion
示例 3: 异步调用方法并使用 A WaitHandle 来等待调用完成示例 3: 异步调用方法并使用 A WaitHandle 来等待调用完成#region 示例 3: 异步调用方法并使用 A WaitHandle 来等待调用完成
/**//**//**//*
* 由 BeginInvoke() 返回 IAsyncResult 具有一个 AsyncWaitHandle 属性。
* 该属性返回 WaitHandle 异步调用完成后, 通知是。 等待 WaitHandle 是常见线程同步技术。
* 通过是 WaitHandle WaitOne() 方法调用线程等待 WaitHandle 上。
* 直到是通知 WaitHandle WaitOne() 块。 当 WaitOne() 返回, 您在调用 EndInvoke() 之前进行一些额外工作。
* 对于执行文件或网络操作, 否则会阻塞调用主线程存为, 以前示例中此技术很有用。
* */
/**//**//**//// <summary>
/// 示例 3: 异步调用方法并使用 A WaitHandle 来等待调用完成
/// </summary>
public void DemoWaitHandle ()
......{
string s ;
int iExecThread;
MethodDelegate dlgt = new MethodDelegate (this.LongRunningMethod) ;
// Initiate the asynchronous call.
IAsyncResult ar = dlgt.BeginInvoke(3000, out iExecThread, null, null);
// Do some useful work here. This would be work you want to have
// run at the same time as the asynchronous call.
// Wait for the WaitHandle to become signaled.
ar.AsyncWaitHandle.WaitOne() ;
// Get the results of the asynchronous call.
s = dlgt.EndInvoke (out iExecThread, ar) ;
Console.WriteLine(string.Format ("The delegate call returned the string: "...{0}", and the number {1}", s, iExecThread.ToString() ) );
}
#endregion
示例 4: 异步调用方法通过轮询调用模式示例 4: 异步调用方法通过轮询调用模式#region 示例 4: 异步调用方法通过轮询调用模式
/**//**//**//*
* 由 BeginInvoke() 返回 IAsyncResult 对象有个 IsCompleted 属性异步调用完成后返回 True 。
* 然后可调用 EndInvoke() 。 如果您应用程序不断工作对不做要长期函数调用已被此调用模式很有用。
* MicrosoftWindows 应用程序是这样的示例。
* 主线程的 Windows 应用程序可以继续以执行异步调用时处理用户输入。
* 它可定期检查 IsCompleted 到调用是否完成。 它调用 EndInvoke 当 IsCompleted 返回 True 。
* 直到它知道操作已完成因为 EndInvoke() 阻止直到异步操作为完整, 应用程序不调用它。
* */
/**//**//**//// <summary>
/// 示例 4: 异步调用方法通过轮询调用模式
/// </summary>
public void DemoPolling()
......{
MethodDelegate dlgt = new MethodDelegate (this.LongRunningMethod) ;
string s ;
int iExecThread;
// Initiate the asynchronous call.
IAsyncResult ar = dlgt.BeginInvoke(3000, out iExecThread, null, null);
// Poll IAsyncResult.IsCompleted
while(ar.IsCompleted == false)
......{
Thread.Sleep (10) ; // pretend to so some useful work
}
s = dlgt.EndInvoke (out iExecThread, ar) ;
Console.WriteLine(string.Format ("The delegate call returned the string: "...{0}", and the number {1}", s, iExecThread.ToString() ) );
}
#endregion
示例 5: 异步方法完成后执行回调示例 5: 异步方法完成后执行回调#region 示例 5: 异步方法完成后执行回调
/**//**//**//*
* 本节, 中示例提供对 BeginInvoke() 函数, 异步调用完成后系统执行回调委托。
* 回调调用 EndInvoke() 并处理异步调用的结果。
* 如果启动异步调用线程不需要处理结果是调用此调用模式很有用。
* 异步调用完成后系统调用线程以外启动线程上调。
* 若使用此调用模式, 作为第二到最后 - BeginInvoke() 函数的参数必须传递 AsyncCallback 类型的委托。
* BeginInvoke() 还有最后参数键入 对象 到您可以将任何对象。 当它调用该对象可用于您回调函数。
* 为此参数一个重要用途是以传递用于初始化调用该委托。
* 回调函数然后使用与该委托 EndInvoke() 函数来完成调用。 此调用模式是所示。
* */
/**//**//**//// <summary>
/// 示例 5: 异步方法完成后执行回调
/// </summary>
public void DemoCallback()
......{
MethodDelegate dlgt = new MethodDelegate (this.LongRunningMethod) ;
string s ;
int iExecThread;
// Create the callback delegate.
AsyncCallback cb = new AsyncCallback(MyAsyncCallback);
// Initiate the Asynchronous call passing in the callback delegate
// and the delegate object used to initiate the call.
IAsyncResult ar = dlgt.BeginInvoke(3000, out iExecThread, cb,dlgt);
}
public void MyAsyncCallback(IAsyncResult ar)
......{
string s ;
int iExecThread ;
// Because you passed your original delegate in the asyncState parameter
// of the Begin call, you can get it back here to complete the call.
MethodDelegate dlgt = (MethodDelegate) ar.AsyncState;
// Complete the call.
s = dlgt.EndInvoke (out iExecThread, ar) ;
Console.WriteLine(string.Format ("The delegate call returned the string: "...{0}", and the number {1}", s, iExecThread.ToString() ) );
}
#endregion
}
}
using System;
using System.Threading;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Remoting.Messaging;
namespace test
{
[Serializable]
public class AsyncDemo
{
public delegate void TestRaiseEventHandler(object sender, EventArgs e);
public event TestRaiseEventHandler TestRaise;
protected virtual void OnTestRaiseEventHandler()
{
if (TestRaise != null)
{
TestRaise(this, null);
}
}
// 将被异步调用的方法
//
public string TestMethod(int callDuration, out int threadId)
{
Console.WriteLine("Test method begins.");
OnTestRaiseEventHandler();
Thread.Sleep(callDuration);
threadId = AppDomain.GetCurrentThreadId();
return "MyCallTime was " + callDuration.ToString();
}
// 序列化操作
public void Serialize(string filename)
{
Serialize(filename, this);
}
public static void Serialize(string filename, AsyncDemo async)
{
FileStream fs = new FileStream(filename, FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, async);
}
finally
{
fs.Close();
}
}
}
// 用来执行异步调用的代理
public delegate string AsyncDelegate(int callDuration, out int threadId);
public class AsyncMain
{
private static int threadId;
static void Main(string[] args)
{
// 创建测试类
AsyncDemo ad = new AsyncDemo();
// 添加事件
.(1)
ad.TestRaise += new test.AsyncDemo.TestRaiseEventHandler((new AsyncMain()).ad_TestRaise);
// 创建异步方法的代理
AsyncDelegate dlgt = new AsyncDelegate(ad.TestMethod);
// 开始执行异步调用
IAsyncResult ar = dlgt.BeginInvoke(1000,
out threadId,
new AsyncCallback(CallbackMethod),
ad );
// 等待调用完成
Console.WriteLine("Press Enter to close application.");
Console.ReadLine();
}
// 事件响应函数
void ad_TestRaise(object sender, EventArgs e)
{
Console.WriteLine("delegate call");
}
// 异步调用完成时的回调函数
static void CallbackMethod(IAsyncResult ar)
{
// 得到异步方法的代理
AsyncDelegate dlgt = (AsyncDelegate) (ar as AsyncResult).AsyncDelegate;
Console.WriteLine("begin EndInvoke");
string ret = dlgt.EndInvoke(out threadId, ar);
Console.WriteLine("The call executed on thread {0}, with return value /"
{1}/".", threadId, ret);
// 执行序列化操作
(2)
AsyncDemo demo = ar.AsyncState as AsyncDemo;
demo.Serialize("Test.dat");
}
}
}
相关文章推荐
- 如何异步调用 Visual C# 方法
- 如何异步调用 Visual C# 方法
- 如何异步调用一个java方法,
- VBScript如何调用异步调用ajaxpro注册的方法
- javascript 异步调用 后台.cs里的方法 PageMethods如何使用
- [转]javascript 异步调用 后台.cs里的方法 PageMethods如何使用
- 在同步方法中调用异步方法时如何避免死锁问题
- oracle学习之道:如何在ORACLE中异步调用存储过程的方法
- 如何在ORACLE中异步调用存储过程的方法
- 如何异步调用方法
- php如何进行多进程与异步调用方法
- vue组件之间的通信以及如何在父组件中调用子组件的方法和属性
- 如何在C/C++中调用Java的方法
- servert 中如何调用spring管理的bean方法
- Unity SLua 如何调用Unity中C#方法
- spring boot 使用@Async实现异步调用方法
- ajax 异步调用方法
- C#如何通过反射调用带有ref或者out的参数的方法
- PHP实现异步调用方法研究
- 如何在razer中调用方法