Create a new thread in VB.NET

2020-06-07 06:49发布

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'.

3条回答
Animai°情兽
2楼-- · 2020-06-07 07:10

It is called a lambda expression in 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:

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
查看更多
够拽才男人
3楼-- · 2020-06-07 07:12

There's two ways to do this;

  1. With the AddressOf operator to an existing method

    Sub MyBackgroundThread()
      Console.WriteLine("Hullo")
    End Sub
    

    And then create and start the thread with;

    Dim thread As New Thread(AddressOf MyBackgroundThread)
    thread.Start()
    
  2. Or as a lambda function.

    Dim thread as New Thread(
      Sub() 
        Console.WriteLine("Hullo")
      End Sub
    )
    thread.Start()
    
查看更多
家丑人穷心不美
4楼-- · 2020-06-07 07:26

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

查看更多
登录 后发表回答