我在一个返回数据表的模块中有一个函数。我需要异步调用该函数并在vb.net的主线程(主窗体)中获取结果。
答案 0 :(得分:2)
您可以使用BackgroundWorker
来执行此操作。
Private WithEvents dataBackgroundWorker As New BackgroundWorker
然后你需要打电话
dataBackgroundWorker.RunWorkerAsync()
提出DoWork
事件
因此,在该处理程序中,您将调用您的函数并通过e.Result
e.Result = yourFunction()
然后在RunWorkerCompleted
事件中,您将e.Result
分配给相应的变量。
答案 1 :(得分:2)
您最好的选择可能是使用后台工作人员。如果你喜欢冒险,Async CTP看起来非常棒。
http://msdn.microsoft.com/en-us/vstudio/gg316360
您可以在此处找到示例:http://www.wischik.com/lu/AsyncSilverlight/AsyncSamples.html
Public Async Function AsyncResponsiveCPURun() As Task
Console.WriteLine("Processing data... Drag the window around or scroll the tree!")
Console.WriteLine()
Dim data As Integer() = Await ProcessDataAsync(GetData(), 16, 16)
Console.WriteLine()
Console.WriteLine("Processing complete.")
End Function
Public Function ProcessDataAsync(ByVal data As Byte(), ByVal width As Integer, ByVal height As Integer) As Task(Of Integer())
Return TaskEx.Run(
Function()
Dim result(width * height) As Integer
For y As Integer = 0 To height - 1
For x As Integer = 0 To width - 1
Thread.Sleep(10) ' simulate processing cell [x,y]
Next
Console.WriteLine("Processed row {0}", y)
Next
Return result
End Function)
End Function