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 !




Prevent sharing of static fields across instances/threads


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

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



As you know, static fields share their values in all the instances of a class. The value of a static field is the same across the multiple thread accesses also. To prevent this sharing, you may use the ThreadStatic attribute applied on the desired field.

Here in this code, x is a static field whose initial value is 10. Then I create three threads and read the value of the field x. You could set the value of x individually for a thread or instance (as in P2 object in this example). Also, note that initial value is not shared by any of the threads.



class Program1
{
[ThreadStatic]
static int x;

static void Main(string[] args)
{
Program1 p1 = new Program1();
x = 10; // initial value
new Thread(delegate() { p1.GetValue(); }).Start();
new Thread(delegate() { p1.SetValue(); }).Start();
new Thread(delegate() { p1.GetValue(); }).Start();
Console.WriteLine(Program1.x);
}

void SetValue()
{
x = 100;
Program1 p2 = new Program1();
x = 50;
p2.GetValue();
}

void GetValue()
{
Console.WriteLine(x);
}
}





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: Implementing ReaderWriterLock for seamless Read and Write Operations
Previous Resource: Thread Synchronization
Return to Discussion Resource Index
Post New Resource
Category: Threading


Post resources and earn money!
 
Related Resources



dotNet Slackers   BizTalk Adaptors    Web Design

budget conference call

Contact Us    Privacy Policy    Terms Of Use