Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread-exclusive data: how to store and access?

Is there a possibility in .NET to bind an object instance to a current execution context of a thread? So that in any part of the code I could do something like CurrentThread.MyObjectData.DoOperation() and be sure that I access thread-specific data? thanks!

like image 347
Andy Avatar asked Feb 22 '10 08:02

Andy


People also ask

How do you restrict access to an object to one thread at a time?

You want to achieve mutual exclusion with doSomeTimeConsumingAction , so that only one thread at a time can be running the doSomeTimeConsumingAction method of an object at a time. Alternatively, use a synchronized block in the threads themselves, which acquires a lock on the object.

Which of the following methods will you use when you want to allow only one thread at a time to access application state variables?

The lock statement is one of the simplest and most common tools for C# developers writing multithreaded applications. It can be used to synchronize access to blocks of code, achieving thread safety by allowing only one thread at a time to execute the code in that block.

How might you ensure that only one thread at a time executes a particular method?

Yes, you can use lock for this. Create a private synchronization object in your class, acquire the lock on this object and only one thread at a time will be able to execute the code within the lock block.

What object allows more threads to enter than others?

A semaphore is very similar to a Mutex but a semaphore can be used by multiple threads at once while a Mutex can't. With a Semaphore, you can define a count of how many threads are allowed to access the resources shielded by a semaphore simultaneously.


1 Answers

You could take a look at the ThreadStaticAttribute. Another helpful methods are SetData/GetData which allow you to store data relative to the current thread.

like image 55
Darin Dimitrov Avatar answered Oct 05 '22 06:10

Darin Dimitrov