Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the skills of multithreaded handle in VB.NET programming

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article to share with you is about VB. NET programming multithreaded handle skills what content. Xiaobian thinks it is quite practical, so share it with everyone for reference. Let's follow Xiaobian and have a look.

VB. NET programming after a long time of development, many users are very familiar with VB. NET programming in multi-threaded procedures. Multithreading has become a chore for most programmers. Now let's talk about multithreading. Multithreading is possible because the operating system is multitasking and has the ability to simulate running multiple applications at the same time. Although most personal computers have only one processor, current operating systems provide for multitasking by dividing processor time between multiple pieces of code executing. A thread may be the entire application, but is usually a part of the application that can run separately. The operating system allocates processing time to each thread based on its priority and how long it has been since it last ran. Multithreading provides a significant performance boost for applications with time-intensive transactions such as file input and output. Three types of wait handles are commonly used in VB. NET programming: Mutex Objects, ManualResetEvents, and AutoResetEvents. The latter two are usually used for synchronous events.

1. mutex

Mutex objects are synchronous objects that can only be owned by a thread at a time. In fact, the name mutex derives from the fact that ownership of mutex objects is mutually exclusive. When threads request exclusive access to a resource, they request ownership of mutex objects. Because only one thread can own a mutex at a time, other threads must wait for ownership of the mutex before using the resource. The WaitOne method raises a calling thread waiting for ownership of the mutex object. If the thread owning the mutex terminates normally, the mutex's state is set to signed and the next thread takes ownership of it.

2. synchronization event

Synchronous events are used to notify other threads that something has happened or that a resource is available. Don't be fooled by its use of the word "incident." Synchronous events differ from other Visual Basic events in that they are true wait handles. Similar to other wait handles, synchronous events have two states: signaled and non-signaled. A thread calling one of the wait methods of a synchronized event must wait until another thread calls the Set method to signal the event. There are two synchronous event classes. The thread uses the Set method to set the state of the ManualResetEvent instance to signed. The thread uses the Reset method or control return to wait for the WaitOne call to set the state of the instance to nonsignaled. Instances of the AutoResetEvent class can also be set to signed using Set, but they automatically return to nonsigned whenever the notification waiting thread event becomes signed.

The following example uses the AutoResetEvent class to synchronize thread pool transactions.

SubStartTest() DimATAsNewAsyncTest() AT.StartTask() EndSub ClassAsyncTest PrivateSharedAsyncOpDoneAsNewSystem.Threading.AutoResetEvent(False) SubStartTask()DimTpoolAsSystem.Threading.ThreadPoolDimargAsString="SomeArg" Tpool.QueueUserWorkItem(NewSystem.Threading.WaitCallback(_AddressOfTask),arg)'Queue a transaction AsyncOpDone.WaitOne()' Wait for the thread to call SetMsgBox("Threaddone. ") EndSubSubTask(ByValArgAsObject) MsgBox("Threadisstarting. ") System. Thread.Thread.Sleep(4000)'Wait 4 seconds. MsgBox("Thestateobjectcontainsthestring"&CStr(Arg)) AsyncOpDone.Set()'signals that the thread has completed EndSub EndClass

3. Monitoring objects and synchronization locks

Monitoring objects ensure that the execution of a block of code is not interrupted by code running in other threads. In other words, code in other threads cannot run until the synchronized block ends. Use the SyncLock keyword in Visual Basic. NET to simplify access to monitored objects. Use the Lock keyword in Visual C#. NET.

For example, suppose you have a program that repeatedly and asynchronously reads data and displays the results. With priority multitasking operating systems, running threads can be interrupted because the operating system allows other threads to run. Without synchronization, objects displaying data are modified by other threads while the data is being displayed, possibly resulting in a partially updated view of the data. SyncLock guarantees that a piece of code runs continuously without interruption. The following example shows how SyncLock can be used to provide exclusive access to data objects for display processes.

ClassDataObject PublicObjTextAsString PublicObjTimeStampAsDate EndClassSubRunTasks() DimMyDataObjectAsNewDataObject() ReadDataAsync(MyDataObject) SyncLockMyDataObject DisplayResults(MyDataObject) EndSyncLock EndSub ReadDataAsync (ByRefMyDataObjectAsDataObject)'Add code for asynchronous reading and processing of data EndSubDisplayResults (ByValMyDataObjectAsDataObject)' Add code for displaying results EndSub

Interlocked class

You can use Interlocked class methods to prevent problems where multiple threads update or compare the same value at the same time. Methods in this class let you safely add, subtract, swap, and compare values from any thread. The following example demonstrates how to use the Increment method to increment the value of a variable shared by multiple procedures running on separate threads.

SubThreadA(ByRefIntAAsInteger) System.Threading.Interlocked.Increment(IntA) EndSub SubThreadB(ByRefIntAAsInteger) System.Threading.Interlocked.Increment(IntA) EndSub

ReaderWriter lock

In some cases, you may want to lock resources only while writing data, allowing multiple clients to read data simultaneously until the data is updated. When a thread is modifying a resource, the ReaderWriterLock class enforces exclusive access to that resource, but allows nonexclusive access to read resources. ReaderWriter locks are a useful alternative to exclusive locks that cause other threads to wait, even if they do not need to update data. The following example demonstrates how to use ReaderWriter to coordinate read and write operations from multiple threads.

ClassReadWrite 'ReadData and WriteData methods can be safely called by multiple threads PublicReadWriteLockAsNewSystem.Threading. ReadWriterLock () SubReadData()' This procedure reads information from a data source. While allowing other threads to call ReadData, the read lock places any data writes until the read is complete ReadWriteLock.AcquireReaderLock(System.Threading.Timeout.Infinite)Try'here to perform the data operation FinallyReadWriteLock.ReleaseReaderLock()' Release the read lock EndTry EndSubWriteData ()'This procedure writes information to the data source. Write locks prevent data from being read or written until the thread completes the write operation. ReadWriteLock.AcquireWriterLock(System.Threading.Timeout.Infinite)Try'Write here FinallyReadWriteLock.ReleaseWriterLock()' Release WriteLock EndTry EndSub EndClass Thank you for reading! About "VB. NET programming multi-thread handle skills what" this article is shared here, I hope the above content can have some help for everyone, so that we can learn more knowledge, if you think the article is good, you can share it to let more people see it!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report