异步方式调用同步方法_第1页
异步方式调用同步方法_第2页
异步方式调用同步方法_第3页
异步方式调用同步方法_第4页
异步方式调用同步方法_第5页
已阅读5页,还剩10页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、窗体顶端窗体底端您查询的关键词是:c# begininvoke endinvoke  。如果打开速度慢,可以尝试快速版;如果想保存快照,可以添加到搜藏。(百度和网页窗体顶端.NET Framework 开发人员指南使用异步方式调用同步方法.NET Framework 允许您异步调用任何方法。为此,应定义与您要调用的方法具有相同签名的委托;公共语言运行库会自动使用适当的签名为该委托定义 BeginInvoke 和 EndInvoke 方法。BeginInvoke 方法可启动异步调用。它与您需要异步执行的方法具有相同的参数,另外它还有两个可选参数。第一个参数是一个 A

2、syncCallback 委托,该委托引用在异步调用完成时要调用的方法。第二个参数是一个用户定义的对象,该对象可向回调方法传递信息。BeginInvoke 立即返回,不等待异步调用完成。BeginInvoke 会返回 IAsyncResult,这个结果可用于监视异步调用进度。EndInvoke 方法检索异步调用的结果。调用 BeginInvoke 后可随时调用 EndInvoke 方法;如果异步调用尚未完成,EndInvoke 将一直阻止调用线程,直到异步调用完成后才允许调用线程执行。EndInvoke 的参数包括您需要异步执行的方法的 out 和 ref 参数(在 Visual Basic

3、中为 <Out>?ByRef 和 ByRef)以及由 BeginInvoke 返回的 IAsyncResult。注意 Visual Studio 2005 中的 IntelliSense 功能显示 BeginInvoke 和 EndInvoke 的参数。如果您没有使用 Visual Studio 或类似工具,或您使用的是带有 Visual Studio 2005 的 C#,请参见异步编程概述以获取为这些方法定义的参数的说明。本主题中的代码示例演示了四种使用 BeginInvoke 和 EndInvoke 进行异步调用的常用方法。调用 BeginInvoke 之后,您可以执行下列操作

4、: · 进行某些操作,然后调用 EndInvoke 一直阻止到调用完成。· 使用 System.IAsyncResult.AsyncWaitHandle 属性获取 WaitHandle,使用它的 WaitOne 方法一直阻止执行直到发出 WaitHandle 信号,然后调用 EndInvoke。· 轮询由 BeginInvoke 返回的 IAsyncResult,确定异步调用何时完成,然后调用 EndInvoke。· 将用于回调方法的委托传递给 BeginInvoke。异步调用完成后,将在 ThreadPool 线程上执行该方法。该回调方法将调用 End

5、Invoke。要点 每次都要调用 EndInvoke 来完成异步调用。定义测试方法和异步委托下面的代码示例演示异步调用同一个长时间运行的方法 TestMethod 的各种方式。TestMethod 方法会显示一条控制台消息,说明它已开始处理,休眠了几秒钟,然后结束。TestMethod 有一个 out 参数,该参数用于演示此种参数添加到 BeginInvoke 和 EndInvoke 的签名中的方式。您可以按同样的方式处理 ref 参数。下面的代码示例演示 TestMethod 的定义和名为 AsyncMethodCaller 的、可用来异步调用 TestMethod 的委托。若要编译任何代码

6、示例,必须包括 TestMethod 的定义和 AsyncMethodCaller 委托。Visual BasicImports SystemImports System.ThreadingImports System.Runtime.InteropServices Namespace Examples.AdvancedProgramming.AsynchronousOperations Public Class AsyncDemo ' The method to be executed asynchronously. Public Function TestMethod(ByVal

7、callDuration As Integer, _ <Out> ByRef threadId As Integer) As String Console.WriteLine("Test method begins.") Thread.Sleep(callDuration) threadId = Thread.CurrentThread.ManagedThreadId() return String.Format("My call time was 0.", callDuration.ToString() End Function End C

8、lass ' The delegate must have the same signature as the method ' it will call asynchronously. Public Delegate Function AsyncMethodCaller(ByVal callDuration As Integer, _ <Out> ByRef threadId As Integer) As StringEnd NamespaceC#using System;using System.Threading; namespace Examples.Adv

9、ancedProgramming.AsynchronousOperations public class AsyncDemo / The method to be executed asynchronously. public string TestMethod(int callDuration, out int threadId) Console.WriteLine("Test method begins."); Thread.Sleep(callDuration); threadId = Thread.CurrentThread.ManagedThreadId; ret

10、urn String.Format("My call time was 0.", callDuration.ToString(); / The delegate must have the same signature as the method / it will call asynchronously. public delegate string AsyncMethodCaller(int callDuration, out int threadId);使用 EndInvoke 等待异步调用异步执行方法最简单的方式是通过调用委托的 BeginInvoke 方法来开始执

11、行方法,在主线程上执行一些工作,然后调用委托的 EndInvoke 方法。EndInvoke 可能会阻止调用线程,因为它直到异步调用完成之后才返回。这种技术非常适合文件或网络操作,但是由于 EndInvoke 会阻止它,所以不要从服务于用户界面的线程中调用它。Visual BasicImports SystemImports System.ThreadingImports System.Runtime.InteropServices Namespace Examples.AdvancedProgramming.AsynchronousOperations Public Class AsyncM

12、ain Shared Sub Main() ' The asynchronous method puts the thread id here. Dim threadId As Integer ' Create an instance of the test class. Dim ad As New AsyncDemo() ' Create the delegate. Dim caller As New AsyncMethodCaller(AddressOf ad.TestMethod) ' Initiate the asynchronous call. Dim

13、 result As IAsyncResult = caller.BeginInvoke(3000, _ threadId, Nothing, Nothing) Thread.Sleep(0) Console.WriteLine("Main thread 0 does some work.", _ Thread.CurrentThread.ManagedThreadId) ' Call EndInvoke to Wait for the asynchronous call to complete, ' and to retrieve the results.

14、 Dim returnValue As String = caller.EndInvoke(threadId, result) Console.WriteLine("The call executed on thread 0, with return value ""1"".", _ threadId, returnValue) End Sub End ClassEnd NamespaceC#using System;using System.Threading;namespace Examples.AdvancedProgrammi

15、ng.AsynchronousOperations public class AsyncMain public static void Main() / The asynchronous method puts the thread id here. int threadId; / Create an instance of the test class. AsyncDemo ad = new AsyncDemo(); / Create the delegate. AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);

16、/ Initiate the asychronous call. IAsyncResult result = caller.BeginInvoke(3000, out threadId, null, null); Thread.Sleep(0); Console.WriteLine("Main thread 0 does some work.", Thread.CurrentThread.ManagedThreadId); / Call EndInvoke to wait for the asynchronous call to complete, / and to ret

17、rieve the results. string returnValue = caller.EndInvoke(out threadId, result); Console.WriteLine("The call executed on thread 0, with return value "1".", threadId, returnValue); 使用 WaitHandle 等待异步调用您可以使用 BeginInvoke 返回的 IAsyncResult 的 AsyncWaitHandle 属性来获取 WaitHandle。异步调用完成时会发出

18、WaitHandle 信号,而您可以通过调用 WaitOne 方法等待它。如果您使用 WaitHandle,则在异步调用完成之前或之后,在通过调用 EndInvoke 检索结果之前,还可以执行其他处理。Visual BasicImports SystemImports System.ThreadingImports System.Runtime.InteropServices Namespace Examples.AdvancedProgramming.AsynchronousOperations Public Class AsyncMain Shared Sub Main() ' T

19、he asynchronous method puts the thread id here. Dim threadId As Integer ' Create an instance of the test class. Dim ad As New AsyncDemo() ' Create the delegate. Dim caller As New AsyncMethodCaller(AddressOf ad.TestMethod) ' Initiate the asynchronous call. Dim result As IAsyncResult = cal

20、ler.BeginInvoke(3000, _ threadId, Nothing, Nothing) Thread.Sleep(0) Console.WriteLine("Main thread 0 does some work.", _ Thread.CurrentThread.ManagedThreadId) ' Perform additional processing here and then ' wait for the WaitHandle to be signaled. result.AsyncWaitHandle.WaitOne() &#

21、39; Call EndInvoke to retrieve the results. Dim returnValue As String = caller.EndInvoke(threadId, result) Console.WriteLine("The call executed on thread 0, with return value ""1"".", _ threadId, returnValue) End Sub End ClassEnd NamespaceC#using System;using System.Thr

22、eading;namespace Examples.AdvancedProgramming.AsynchronousOperations public class AsyncMain static void Main() / The asynchronous method puts the thread id here. int threadId; / Create an instance of the test class. AsyncDemo ad = new AsyncDemo(); / Create the delegate. AsyncMethodCaller caller = ne

23、w AsyncMethodCaller(ad.TestMethod); / Initiate the asychronous call. IAsyncResult result = caller.BeginInvoke(3000, out threadId, null, null); Thread.Sleep(0); Console.WriteLine("Main thread 0 does some work.", Thread.CurrentThread.ManagedThreadId); / Wait for the WaitHandle to become sign

24、aled. result.AsyncWaitHandle.WaitOne(); / Perform additional processing here. / Call EndInvoke to retrieve the results. string returnValue = caller.EndInvoke(out threadId, result); Console.WriteLine("The call executed on thread 0, with return value "1".", threadId, returnValue);

25、轮询异步调用完成您可以使用由 BeginInvoke 返回的 IAsyncResult 的 IsCompleted 属性来发现异步调用何时完成。从用户界面的服务线程中进行异步调用时可以执行此操作。轮询完成允许调用线程在异步调用在 ThreadPool 线程上执行时继续执行。Visual BasicImports SystemImports System.ThreadingImports System.Runtime.InteropServices Namespace Examples.AdvancedProgramming.AsynchronousOperations Public Class

26、 AsyncMain Shared Sub Main() ' The asynchronous method puts the thread id here. Dim threadId As Integer ' Create an instance of the test class. Dim ad As New AsyncDemo() ' Create the delegate. Dim caller As New AsyncMethodCaller(AddressOf ad.TestMethod) ' Initiate the asynchronous ca

27、ll. Dim result As IAsyncResult = caller.BeginInvoke(3000, _ threadId, Nothing, Nothing) ' Poll while simulating work. While result.IsCompleted = False Thread.Sleep(10) End While ' Call EndInvoke to retrieve the results. Dim returnValue As String = caller.EndInvoke(threadId, result) Console.W

28、riteLine("The call executed on thread 0, with return value ""1"".", _ threadId, returnValue) End Sub End ClassEnd NamespaceC#using System;using System.Threading;namespace Examples.AdvancedProgramming.AsynchronousOperations public class AsyncMain static void Main() / The

29、 asynchronous method puts the thread id here. int threadId; / Create an instance of the test class. AsyncDemo ad = new AsyncDemo(); / Create the delegate. AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod); / Initiate the asychronous call. IAsyncResult result = caller.BeginInvoke(3000,

30、out threadId, null, null); / Poll while simulating work. while(result.IsCompleted = false) Thread.Sleep(10); / Call EndInvoke to retrieve the results. string returnValue = caller.EndInvoke(out threadId, result); Console.WriteLine("The call executed on thread 0, with return value "1".&

31、quot;, threadId, returnValue); 异步调用完成时执行回调方法如果启动异步调用的线程不需要是处理结果的线程,则可以在调用完成时执行回调方法。回调方法在 ThreadPool 线程上执行。若要使用回调方法,必须将引用回调方法的 AsyncCallback 委托传递给 BeginInvoke。也可以传递包含回调方法将要使用的信息的对象。例如,可以传递启动调用时曾使用的委托,以便回调方法能够调用 EndInvoke。Visual BasicImports SystemImports System.ThreadingImports System.Runtime.Interop

32、Services Namespace Examples.AdvancedProgramming.AsynchronousOperations Public Class AsyncMain ' The asynchronous method puts the thread id here. Private Shared threadId As Integer Shared Sub Main() ' Create an instance of the test class. Dim ad As New AsyncDemo() ' Create the delegate. D

33、im caller As New AsyncMethodCaller(AddressOf ad.TestMethod) ' Initiate the asynchronous call. Dim result As IAsyncResult = caller.BeginInvoke(3000, _ threadId, _ AddressOf CallbackMethod, _ caller) Console.WriteLine("Press Enter to close application.") Console.ReadLine() End Sub '

34、Callback method must have the same signature as the ' AsyncCallback delegate. Shared Sub CallbackMethod(ByVal ar As IAsyncResult) ' Retrieve the delegate. Dim caller As AsyncMethodCaller = CType(ar.AsyncState, AsyncMethodCaller) ' Call EndInvoke to retrieve the results. Dim returnValue As String = caller.EndInvoke(threadId, ar) Console.WriteLine("The call executed on thread 0, with return value ""1"".", _ threadId, returnValue) End Sub End ClassEnd NamespaceC#using System;

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论