在 VB.NET 中创建一个新线程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10182563/
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
Create a new thread in VB.NET
提问by Matt9Atkins
I am trying to create a new thread using an anonymous function but I keep getting errors. Here is my code:
我正在尝试使用匿名函数创建一个新线程,但我不断收到错误消息。这是我的代码:
New Thread(Function()
// Do something here
End Function).Start
Here are the errors I get:
以下是我得到的错误:
New:
新的:
Syntax Error
语法错误
End Function:
结束函数:
'End Function' must be preceded by a matching 'Function'.
'End Function' 前面必须有一个匹配的 'Function'。
回答by MrMDavidson
There's two ways to do this;
有两种方法可以做到这一点;
With the
AddressOf
operator to an existing methodSub MyBackgroundThread() Console.WriteLine("Hullo") End Sub
And then create and start the thread with;
Dim thread As New Thread(AddressOf MyBackgroundThread) thread.Start()
Or as a lambda function.
Dim thread as New Thread( Sub() Console.WriteLine("Hullo") End Sub ) thread.Start()
使用
AddressOf
操作符对现有方法进行操作Sub MyBackgroundThread() Console.WriteLine("Hullo") End Sub
然后创建并启动线程;
Dim thread As New Thread(AddressOf MyBackgroundThread) thread.Start()
或者作为 lambda 函数。
Dim thread as New Thread( Sub() Console.WriteLine("Hullo") End Sub ) thread.Start()
回答by Hans Passant
It is called a lambda expressionin VB. The syntax is all wrong, you need to actually declare a variable of type Thread to use the New operator. And the lambda you create must be a valid substitute for the argument you pass to the Thread class constructor. None of which take a delegate that return a value so you must use Sub, not Function. A random example:
它在 VB 中称为lambda 表达式。语法全错了,你需要实际声明一个 Thread 类型的变量才能使用 New 运算符。您创建的 lambda 必须是您传递给 Thread 类构造函数的参数的有效替代品。其中没有一个接受返回值的委托,因此您必须使用 Sub,而不是 Function。一个随机的例子:
Imports System.Threading
Module Module1
Sub Main()
Dim t As New Thread(Sub()
Console.WriteLine("hello thread")
End Sub)
t.Start()
t.Join()
Console.ReadLine()
End Sub
End Module
回答by IvanH
What is called has to be a functinon not a sub.
所谓的必须是函数而不是子函数。
Single line(has to return value):
单行(必须返回值):
Dim worker As New Thread(New ThreadStart(Function() 42))
Multiline:
多行:
Dim worker As New Thread(New ThreadStart(Function()
' Do something here
End Function))
Source: Threading, Closures, and Lambda Expressions in VB.Net