天天看點

vb.net異步操作示例

IAsyncResult 接口由包含可異步操作的方法的類實作。

它是啟動異步操作的方法的傳回類型,如 FileStream.BeginRead1,

也是結束異步操作的方法的第三個參數的類型,如 FileStream.EndRead2。

當異步操作完成時,IAsyncResult 對象也将傳遞給由 AsyncCallback3 委托調用的方法。

支援 IAsyncResult 接口的對象存儲異步操作的狀态資訊,并提供同步對象以允許線程在操作完成時終止。

有關如何使用 IAsyncResult 接口的詳細說明,請參見“使用異步方式調用同步方法4”主題。

下面的示例說明如何使用 IAsyncResult 來擷取異步操作的傳回值。

Imports System
Imports System.Threading
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Contexts
Imports System.Runtime.Remoting.Messaging

'' Context-Bound type with Synchronization Context Attribute' <Synchronization()>
Public Class SampleSyncronized
    Inherits ContextBoundObject
    ' A method that does some work - returns the square of the given number
    Public Function Square(ByVal i As Integer) As Integer
        Console.Write("SampleSyncronized.Square called. ")
        Console.WriteLine("The hash of the current thread is: {0}", Thread.CurrentThread.GetHashCode())
        Return i * i
    End Function
    'Square
End Class
'SampleSyncronized'
           
' Async delegate used to call a method with this signature asynchronously'
Delegate Function SampSyncSqrDelegate(ByVal i As Integer) As Integer
'Main sample class
Public Class AsyncResultSample
    Public Shared Sub Main()
        Dim callParameter As Integer = 0
        Dim callResult As Integer = 0
        'Create an instance of a context-bound type SampleSynchronized'Because SampleSynchronized is context-bound, the object    sampSyncObj 'is a transparent proxy
         ‘定義
           
Dim sampSyncObj As New SampleSyncronized()
        'call the method synchronously 
        Console.Write("Making a synchronous call on the object. ")
        Console.WriteLine("The hash of the current thread is: {0}", Thread.CurrentThread.GetHashCode())
        callParameter = 10
        callResult = sampSyncObj.Square(callParameter)
        ‘同異操作方法
           
Console.WriteLine("Result of calling sampSyncObj.Square with {0} is {1}.", callParameter, callResult)
        Console.WriteLine("")
        Console.WriteLine("") 'call the method asynchronously 
        Console.Write("Making an asynchronous call on the object. ")
        Console.WriteLine("The hash of the current thread is: {0}", Thread.CurrentThread.GetHashCode())
        ’異步操作方法
           
Dim sampleDelegate As New SampSyncSqrDelegate(AddressOf sampSyncObj.Square)
        callParameter = 17
        Dim aResult As IAsyncResult = sampleDelegate.BeginInvoke(callParameter, Nothing, Nothing)
        'Wait for the call to complete 
        aResult.AsyncWaitHandle.WaitOne()
        callResult = sampleDelegate.EndInvoke(aResult)
        Console.WriteLine("Result of calling sampSyncObj.Square with {0} is {1}.", callParameter, callResult)

        Console.ReadLine()

    End Sub
    'Main
End Class 'AsyncResultSample
           

繼續閱讀