Vb. NET multithreading Getting Started

Source: Internet
Author: User

A recent project has encountered a slow blocking user interface operation problem, so you want to use multithreading to solve.

In the loop that processes the data, create a new thread to process the data in the new thread. Multithreading processes data at the same time, which speeds up the process and makes user interface operations smoother.

In a multi-tasking operating system. We are able to perform multiple tasks at the same time under the coordination of the operating system. Each task is performed in the form of a time-sharing reuse.

The Windows operating system manages processes through process IDs. Each process consists of at least one thread. A thread is a fragment of a program that can execute independently in a process. When the main program executes, the main program can start the thread. The thread executes at the same time as the main program.

Threads are the smallest unit of time-sharing in a system, which means that threads can execute in parallel with the main program. Participate in the same time-sharing processing. Threads have their own independent stack processing data. It can share the variables and functions defined by the main program when it executes at the same time as the main program. Only the end of the thread execution will return control to the main program.

The most straightforward way to create a thread is to create a new instance of the thread class and use the address of statement to pass the commit for the executed procedure.

However, such a method cannot pass parameters and return values.

We are able to wrap a process that executes in a separate thread into a class or struct. Give them a reference and enable them to return the number of references.

The following is a small demo of a new thread:

Class Tasksclass public Strarg as String public RetVal as a Boolean public Resultflag as a Boolean public Event Resultev        ENT (ByVal Resultflag as Boolean) public Sub sometask () ' uses the Strarg field as a number of parameters. MessageBox.Show ("Strarg includes string" & Strarg) RetVal = True ' Sets the return value of the parameter. 

End subend Class

Public Class Test    Private Sub test_load (sender as Object, e as EventArgs) Handles mybase.load        DoWork ()    End Sub    ' to use the class. Set the attribute or field that stores the parameters,    ' then. The method needs to be called asynchronously.

Sub DoWork () Dim Tasks As New Tasksclass () Dim Thread1 As New System.Threading.Thread (AddressOf tasks.sometask) C8/>tasks.strarg = "parameter A" sets the field to use as the number of parameters. Thread1.start () ' starts a new thread. thread1.join () ' waits for thread 1 execution to finish.

' Displays the return value.

MessageBox.Show ("Thread 1 return value" & Tasks.retval) End subend Class

Such a thread was created.


But actually. Creating too many threads can actually affect performance. Because of the time-sharing between the various threads, the operating system needs to switch between them constantly. When there are too many threads, a lot of time is consumed on the thread switch.

So you need to control the number of threads.

If we just create a new 10 threads, the remaining data waits for some of the 10 threads to end, and then continues to create new threads to process the data.

Keeps the total number of threads at 10.

Public class Threadingobj public paper as WorkSpace public Sub threadinginsertpaper () ' Multithreading data End subend classprivate Paperlist as List (of WorkSpace) = new List (of WorkSpace) Dim threadinglist as List (of System.Threading.Thread) = new List (O F System.Threading.Thread) 
For every paper in paperlist ' multithreading paperlist if Threadinglist.count < Then ' less than 10 threads continue with new thread Dim Th Readingobject as new Threadingobj Dim Threadingtask_1 as New System.Threading.Thread (AddressOf threadingobject.th Readinginsertpaper) Threadingobject.paper = Paper Threadinglist.add (threadingtask_1) threadingt      Ask_1.start () ' starts a new thread.                  Else Dim Goonflag as Boolean = False ' Loop waits for thread end do If checkthreadingstatus () Then ' There are completed threads If threadinglist.count <= and Dim threadingobject As new Threadingobj Dim Threadingtask_1 as New System.Threading.Thread (AddressOf Threadingobject.thre Adinginsertpaper) Threadingobject.paper = Paper Threadinglist.add (threadingtask_                      1) threadingtask_1.start () ' Start a new thread. Goonflag = True End If             Else ' All threads are in progress end If Loop Until goonflag = True End IfNext 
Function Checkthreadingstatus () as Boolean    ' returns true to indicate that there are completed threads    If threadinglist.count <=        Threadingtaskitem in Threadinglist            ' threadingtaskitem.isalive            If threadingtaskitem.isalive = False                Then Threadingtaskitem.abort ()                threadinglist.remove (threadingtaskitem)                Return True            End If        Next    End if    Threading.Thread.Sleep (+)    if Threadinglist.count <= and for each        Threadingtaskitem in Threadinglist            If threadingtaskitem.isalive = False then                Return True            End if        Next    End If    Return FalseEnd Function

If there are 50 active threads in the operating system. If our program has only one thread. Then the program takes up one of the 50 points of system resources. If you open one more thread at this point, it takes up 2/51 of the system's resources. The more resources our program consumes. Processing speed will be faster.

Because of the time-sharing between threads, the number of active threads can also affect the efficiency of the program.

There is a claim that the number of 2N + 2 threads. is the most efficient. n is the number of cores of the CPU.

But the argument has always been controversial.

My test results such as the following (My computer is i7 4770. Quad Core Eight threads):

Number of threads 1 2 3 4 5 6 7 8 9 10 11 15
Take 753 409 345 316 305 286 280 282 273 273 264 266

The result of the test was a bit strange.

。。

may be related to some other factors as well.

For example, the state of a db, for example, to browse the CPU occupied by the Web

Vb. NET multithreading Getting Started

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.