Visual Basic .NET:如何从具有参数的方法中创建任务 [英] Visual Basic .NET: how to create a task from a method with parameters

查看:81
本文介绍了Visual Basic .NET:如何从具有参数的方法中创建任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有参数的子方法:

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)

我会在async函数中转换mysub.在线教程(例如,)仅适用于没有参数的方法.

I would transform mysub in an async function. The online tutorials (this one for example) are only for methods without parameters.

我尝试过:

Dim mytask As Task
Dim x1 as String = "hello"
mytask = New Task(Me.mysub, x1)
mytast.Start()

但是我得到了错误:

未为'Public Sub'的参数'x'指定错误BC30455参数 mysub(x作为对象)'

Error BC30455 Argument not specified for parameter 'x' of 'Public Sub mysub(x As Object)'

推荐答案

使用子 method 将使代码继续在paralell中运行,包括主代码和子代码.请注意,这可能会导致竞争条件(请参阅此处),那么您将无法完全"利用异步/等待便捷的编程.这与您在一开始建议的多线程应用程序完全相同.

Using a sub method will 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.

在VB中,您需要创建一个lambda自定义子项来调用代码,然后可以传递任何参数:

In VB you need to make a lambda custom sub for calling your code, then you can pass any parameter:

    Dim t As Task
    t = New Task(Sub() mysub(param))

    Public Sub mysub(ByVal param As ParamObject)
        [...]
    End Sub

但是,为了完整起见,我们还考虑另外使用 function .所有函数都返回一些信息,通过使用await关键字,它将强制代码执行暂停,直到结果准备好为止.

However, for completeness of the answer, let's consider additionally using a function as well. All functions return some information and by using the await keyword it will force the code execution to pause until the result is ready.

在VB中,您需要定义一个lambda自定义函数,包括返回类型.然后,您可以调用包含所有所需参数的函数.

Here in VB you need to define a lambda custom function including return type. Then you can call your function including any needed parameters.

    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

您在这里所做的是用于同步代码的async包装函数.不建议这样做有很多原因(请参见此处).始终建议您从头开始编写代码,以从地下室获取async-await行为.

What you are doing here is an async wrapper function for sync code. This is discouraged for many reasons (see here). It's always recommended to write code from scratch which takes async-await behavior from the basement.

这篇关于Visual Basic .NET:如何从具有参数的方法中创建任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆