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'.
In VB.NET, we can create a thread by extending the Thread class and pass the ThreadStart delegate as an argument to the Thread constructor. A ThreadStart() is a method executed by the new thread. We need to call the Start() method to start the execution of the new thread because it is initially in the unstart state.
In visual basic, the thread is a basic unit of execution within the process and it is responsible for executing the application logic. By default, every program will carry one thread to execute the program logic and that thread is called the Main thread. In visual basic, to work with threads we need to import System.
Multi-threading is a process that contains multiple threads within a single process. Here each thread performs different activities. For example, we have a class and this call contains two different methods, now using multithreading each method is executed by a separate thread.
There's two ways to do this;
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()
Or as a lambda function.
Dim thread as New Thread( Sub() Console.WriteLine("Hullo") End Sub ) thread.Start()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With