vb.net异步操作示例

前端之家收集整理的这篇文章主要介绍了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}.",callResult)

        Console.ReadLine()

    End Sub
    'Main
End Class 'AsyncResultSample
原文链接:https://www.f2er.com/vb/260996.html

猜你在找的VB相关文章