C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Communities   Interview   Jobs   Projects   Offshore Development    
Silverlight Tutorials | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Revenue Sharing |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...

New Feature: Community Sites: Create your own .NET community website and start earning from Google AdSense ! It's Free !




Lock a single variable in multi-threaded applications


Posted Date: 27 Mar 2007    Resource Type: Code Snippets    Category: Threading

Posted By: Balamurali Balaji       Member Level: Diamond
Rating:     Points: 10



Instead of locking the entire object using the lock() statement in C#, the following code uses the InterLocked Class to perform thread-safe write operation on a variable. Because the following example uses the shared variable, the new value for the variable is available in both the threads.



static int x = 100;
static void Main(string[] args)
{
Thread t1 = new Thread(delegate() { UpdateValue(); });
t1.Start();
Thread t2 = new Thread(delegate() { UpdateValue(); });
t2.Start();
}

static void UpdateValue()
{
Console.WriteLine("Output:");

// Value of x is set to 30 here
if (Interlocked.Exchange(ref Sample.x, 30) == 0)
{
Console.WriteLine("{0} static value is {1}", Thread.CurrentThread.Name, x);
// Variable x is released after setting the value
Interlocked.Exchange(ref Sample.x, 0);
}
else
{
Console.WriteLine("{0} is denied access to the static value x", Thread.CurrentThread.Name);
}
}





Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Thread Synchronization
Previous Resource: How to schedule a method execution in C#?
Return to Discussion Resource Index
Post New Resource
Category: Threading


Post resources and earn money!
 
Related Resources



dotNet Slackers   BizTalk Adaptors    Web Design

fax server

Contact Us    Privacy Policy    Terms Of Use