Library tutorials & articles
Multithreading in VB.NET
Mutex Class
The next class in our list, Mutex, can be thought of as a more powerful version of Monitor. Like AutoResetEvent and ManualResetEvent, it is derived from WaitHandle. An advantage of Mutex over Monitor is that you can use the methods from WaitHandle such as WaitOne. A disadvantage is that is much slower, at about half as fast as Monitor. Mutex is very useful when you must control access to a resource that could be accessed through multiple processes, like a data file used by several applications you have created. To write to the file, the writing thread must have total access to the file throughout the operating system.
When you create a Mutex, you can assign it a name. If the name exists anywhere in the operating system then that Mutex object instance will be returned. This is the reason why Mutex is slower, also. The system must be checked to see if the Mutex already exists. If it doesn’t exist, a new one is created. When the last thread in the operating system that references the named Mutex terminates, the Mutex is destroyed. The following code example shows how to use a Mutex to control access to a file.
Our first program:
Dim mutexFile As Mutex
Private Sub btnSetMutex_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnSetMutex.Click
mutexFile = New Mutex(False, "Mutex Name")
mutexFile.WaitOne()
'do some file manipulation here such as write to it
'For demonstration purposes we will release
'the mutex in another button click
End Sub
Private Sub btnRelease_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnRelease.Click
mutexFile.ReleaseMutex()
End Sub
Our Second Program
Private Sub btnAquireMutex_Click(ByVal sender As _
System.Object, ByVal e As System.EventArgs) Handles
btnAquireMutex.Click()
Dim mutexFile As Mutex
mutexFile = New Mutex(False, "Mutex Name")
mutexFile.WaitOne() 'Wait until the file is open
Console.WriteLine("Mutex was released from another process")
'Now I know that I have explicit access to the file
'I can write to it now.
mutexFile.ReleaseMutex()
End Sub
Let’s examine the first program. A Mutex called mutexFile is created. Internally to the operating system, we name the mutex “Mutex Name”. This is the name that will be used to resolve any other calls to the same mutex from any other application that we create. On a form we have two buttons. For demonstration purposes, one button will acquire a lock on the resource, in this case the file, using the Mutex and the other button will release the lock. This simulates a long running process on the file. As with the other synchronization classes, you should make sure to call RelaseMutex sometime after a lock is acquired or a block on the resource will occur.
The second program is very straightforward. We create a Mutex object called fileMutex making sure we have named it the same as in the first program, “Mutex Name”. If this is not done the Mutex classes will refer to different mutexes in the operating system. Then WaitOne is called without a timeout value. This will make the thread wait until the Mutex has been released. When the release button is clicked in the first program, the second can continue running since it can now acquire access to the resource. Mutex was released from another process is printed in the output window. You can also close the first program and the lock will be released. When a thread exits that has a Mutex lock on a resource, ReleaseMutex is automatically called for you.
In summary, remember that Monitor should be used most of the time. It is faster than a Mutex. Mutex should only be used when you need to synchronize across multiple processes to gain access to a common resource among several programs that you have written. Even though Mutex allows for the wait methods where Monitor does not, the other WaitHandle classes should be considered before Mutex if you need the wait methods first.
Related articles
Related discussion
-
Multithreading Modal Form/Message
by Akhtar Hussain (0 replies)
-
How to write the category attribut in a class dynamically
by converter2009 (1 replies)
-
VB.NET: Hide and show table using radio buttons
by converter2009 (1 replies)
-
VB.Net Button Problem
by pysdex (0 replies)
-
Unable to access AxInterop.AcoPdflib.dll on 64 bit OS
by Shaila14041981 (0 replies)
Related podcasts
-
Concurrency Pt. 2
Podcast (MP3): Download Hosts: Alexander Michael Guests: Recording venue: In this second part of our concurrency series Michael and Alexander talk about basic patterns for concurrent programming, such as Active and Monitor Object, Scoped Locking and ...
I need to lock the Log file once someone is using it and second person shouldn't able to write in log file. The code is shown below :
Imports System Imports System.IO
Module FileTransfer
End Module
!--removed tag-->Bundle of thanks to the author, it is very help full
As somewhat of an advanced "newbie" I have read many articles on Multithreading, and am at a loss
Do I need to have a delegate and call the delegate when I am using threading ?
Lets say I have a datatable with 5 million rows and I need to iterate through each row - grab some info , process that info (translate it) and then save it somewhere else. For example insert it inot a completely different database (and maybe even RDBMS - Architectur)
Now I currently for each row - but that takes a lot of time.
I would like to spawn a (Flexible Number of threads) to do the row processing - Will my For each move on as each thread runs. So I start Thread(1) will the next trigger, and I have a new row and can start thread(2) and so on. Also my Subroutine, must
Yes, but I decided not to go into detail since it's a vb.net article and you can't use it
Volatility means a lot more than is described in the article. It doesn't just affect the variable which has the volatile modifed; it affects the whole memory model for sections of code involving access to that variable.
I agree that there's no use of volatile which can't be semantically achieved using locks, and indeed I generally prefer to use locks myself. However, there is a speed difference between acquiring a lock and just using a volatile variable - in a very few cases it might be significant. I'm surprised VB.NET doesn't have any way of specifying this.
See the volatility page of my C# threading article for more information.
Jon Skeet
This thread is for discussions of Multithreading in VB.NET.