vb.net Visual Basic .NET:如何从带参数的方法创建任务
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37964024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Visual Basic .NET: how to create a task from a method with parameters
提问by Marco Sulla
I have a sub method with a parameter:
我有一个带参数的子方法:
Public Sub mysub(ByVal x As Object)
[...]
End Sub
To launch it as a thread, I do simply:
要将其作为线程启动,我只需执行以下操作:
Dim x1 as String = "hello"
mythread = New Thread(AddressOf mysub)
mythread.Start(x1)
I would transform mysubin an asyncfunction. The online tutorials (this onefor example) are only for methods without parameters.
我会mysub在一个async函数中进行转换。在线教程(例如本教程)仅适用于没有参数的方法。
I tried with:
我试过:
Dim mytask As Task
Dim x1 as String = "hello"
mytask = New Task(Me.mysub, x1)
mytast.Start()
but I get the error:
但我收到错误:
Error BC30455 Argument not specified for parameter 'x' of 'Public Sub mysub(x As Object)'
错误 BC30455 未为“Public Sub mysub(x As Object)”的参数“x”指定参数
回答by JCM
Using a sub methodwill cause code to continue running in paralell, both main and sub code. Notice this might lead to race-conditions (see here), and also you won't be able to 'fully' take advantage of the async / await convenient programming. This is exactly the same scenario as the multi-thread app you suggested at the beginning.
使用 submethod将导致代码继续并行运行,包括主代码和子代码。请注意,这可能会导致竞争条件(请参阅此处),而且您将无法“完全”利用 async/await 方便的编程。这与您在开始时建议的多线程应用程序完全相同。
In VB you need to make a lambdacustom sub for calling your code, then you can pass any parameter:
在 VB 中,您需要创建一个lambda自定义子来调用您的代码,然后您可以传递任何参数:
Dim t As Task
t = New Task(Sub() mysub(param))
Public Sub mysub(ByVal param As ParamObject)
[...]
End Sub
However, for completeness of the answer, let's consider additionally using a functionas well. All functions return some information and by using the awaitkeyword it will force the code execution to pause until the result is ready.
但是,为了答案的完整性,让我们考虑另外使用 a function。所有函数都返回一些信息,通过使用await关键字,它将强制代码执行暂停,直到结果准备好。
Here in VB you need to define a lambda custom function including return type. Then you can call your function including any needed parameters.
在 VB 中,您需要定义一个包含返回类型的 lambda 自定义函数。然后你可以调用你的函数,包括任何需要的参数。
Dim t As Task(Of RetObject)
t = Task.Run(Function() As RetObject
Return myfunction(param)
End Function)
Return Await t
Public Function myfunction(ByVal param As ParamObject) As RetObject
[...]
End Function
What you are doing here is an asyncwrapper function for sync code. This is discouraged for many reasons (see here). It's always recommended to write code from scratch which takes async-awaitbehavior from the basement.
您在这里所做的是async同步代码的包装函数。出于多种原因,不鼓励这样做(请参阅此处)。始终建议从头开始编写代码,这些代码采用async-await地下室的行为。

