.Net Threading, Part II
This is the second article of two partson dotNet threading. In this second part, I will discuss further thesynchronization objects in the System.Threading dotNet namespace, thread localstorage, COM interoperability and thread states.
Intermediate Level
This article is written for theintermediate and senior C# developer. Working knowledge of the C# programminglanguage and dotNet framework is assumed. The article was written with a Betaversion of VS.NET and associated documentation. Changes, although notanticipated, might occur before final release of VS.NET that invalidateportions of this article.
In the first article, I discussed how tocreate threads, thread pools and some of the synchronization objects availablein the System.Threading dotNet namespace. In this second article, I willcomplete my discussion of the synchronization objects and will discuss threadlocal storage, COM interoperability and thread states.
ReaderWriterLock
Another popular design pattern introducedas a class in the dotNet framework is the ReaderWriterLock. This class allowsan unlimited amount of read locks or one write lock, but not both. This allowsanyone to read the protected resource, as long as nobody is writing to the protectedresource and allows only one thread to write to the protected resource at anyone time. Listing 1 presents a sample using the ReaderWriterLock class.
Listing 1:ReaderWriterLock Class
using System;
using System.Threading;
<!–[if !supportEmptyParas]–> <!–[endif]–><o:p></o:p>
namespace ConsoleApplication9
{
??class Class1
??{
?????public Class1()
?????{
????????rwlock = new ReaderWriterLock();
????????val = "Writer Sequence Number is 1";
?????}
<!–[if !supportEmptyParas]–> <!–[endif]–><o:p></o:p>
?????private ReaderWriterLock rwlock;
?????private string val;
<!–[if !supportEmptyParas]–> <!–[endif]–><o:p></o:p>
?????public void Reader()
?????{
????????rwlock.AcquireReaderLock(Timeout.Infinite);
????????Console.WriteLine("Acquired Read Handle: "
??????????? "Value = {0}", val);
????????Thread.Sleep(1);
????????Console.WriteLine("Releasing Read Handle");
????????rwlock.ReleaseReaderLock();
?????}
<!–[if !supportEmptyParas]–> <!–[endif]–><o:p></o:p>
?????public void Writer()
?????{
????????rwlock.AcquireWriterLock(Timeout.Infinite);
????????Console.WriteLine("Acquired Write Handle");
????????int id = rwlock.WriterSeqNum;
????????Console.WriteLine("Writer Sequence Number "
??????????? "is {0}", id);
????????Thread.Sleep(1);
????????val = "Writer ";
????????Thread.Sleep(1);
>??












No comments yet... Be the first to leave a reply!