Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a new thread in VB.NET

Tags:

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

like image 486
Matt9Atkins Avatar asked Apr 16 '12 22:04

Matt9Atkins


People also ask

How do you create a thread in Visual Basic?

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.

What is thread in visual programming?

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.

What is multithreading in .NET with example?

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.


2 Answers

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() 
like image 99
MrMDavidson Avatar answered Dec 07 '22 21:12

MrMDavidson


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 
like image 42
Hans Passant Avatar answered Dec 07 '22 21:12

Hans Passant