Using Wait Handles and the Mutex Class

Wait handles are wrappers around a Windows feature called synchronization handles. Several .NET synchronization primitives that are based on wait handles, and they all derive from the System.Threading.WaitHandle class. Each class has slightly different characteristics, and we'll walk through each of them in the next chapter when we explore coordinating Tasks.

The wait handle class that has most relevance to avoiding data races and is System.Threading.Mutex. Listing 3-11 shows the basic use of the Mutex class to solve the bank account data race problem. You acquire the lock on Mutex by calling the WaitOne() method and release the lock by calling ReleaseMutex().

Listing 3-11. Basic Use of the Mutex Class using System;

using System.Threading;

using System.Threading.Tasks;

namespace Listing_11 {

class BankAccount {

public int Balance { get; set;

class Listing_ll {

static void Main(string[] args) {

// create the bank account instance BankAccount account = new BankAccount();

// create an array of tasks Task[] tasks = new Task[l0];

for (int i = 0; i < 10; i++) { // create a new task tasks[i] = new Task(() => {

// enter a loop for 1000 balance updates for (int j = 0; j < 1000; j++) { // acquire the mutex bool lockAcquired = mutex.WaitOne(); try {

// update the balance account.Balance = account.Balance + l; } finally {

// release the mutext if (lockAcquired) mutex.ReleaseMutex();

// wait for all of the tasks to complete Task.WaitAll(tasks);

// write out the counter value

Console.WriteLine("Expected value {0}, Balance: {l}", 10000, account.Balance);

// wait for input before exiting Console.WriteLine("Press enter to finish"); Console.ReadLine();

0 0

Post a comment