lock(variable) - conflicting explanation of the variable [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
The docs don't explain it. They only say what should be locked on and what not.
From here it seems like the same object should be used by all threads for the lock to work. While from here it seems that that is exactly what should be avoided to prevent deadlock.
Keep in mind that I might be misunderstanding this whole matter of lock, because I just asked a question about how to "lock" a variable and got what seems to me not to achieve that at all (except locking code).

Think of a lock as a "talking stick" that is used in some meetings. Whoever is holding the stick can talk. Anyone that wants to talk must wait until the speaker relinquishes the stick.
When a piece of code acquires a lock on an object, any other piece of code that requests a lock on that same object must wait until the original code releases the lock.
So which object should you lock? It depends greatly on the context. The rule of thumb is you lock an object that anyone else who could affect the code block can lock as well. If you're updating a collection, then you can ICollection.SyncRoot as an example.
EDIT by OP (Hopefully correct):
"Anyone that wants to talk" - As the speaker "of that stick". (Anyone can just talk.)
As for the second link in the question - it's referring to a problem of one lock waiting for a second, while the second is waiting for the first.

lock should be used around any shared resource. By "shared resource" I mean anything that is accessed by more than one thread.
All a lock does is:
Incoming thread wants access to a piece of code, encounters lock
Lock is empty, thread is allowed in
Thread gets switched out
Another thread wants access to the same code (or code locked on the same variable), encounters lock
Variable is already locked, thread has to wait
Original thread is switched back in, exits locked code
Second thread is switched back in, executes the locked code
If it is possible to have threads in a lock and waiting on another lock at the same time, that then waits on the first lock, you have a gridlock condition. Typically you don't "nest" your locks to avoid this problem. Also, for performance if nothing else, you rarely lock on the same variable as another unless you actually have both pieces relying on the code not executing concurrently (probably a bad design if it is so :) )

Locking something is intended to protect a piece of shared memory. So, you have to use the same SyncRoot for a specific element that you are protecting... However, say you have 3 objects that need to be protected, and they are in no way related:
A a = new A();
B b = new B();
C c = new C();
Then there is NO reason to use the same SyncRoot for all 3 of them. In fact, if they are truly separate, it would be inefficient.

Related

Several locks in one thread, why might they be needed? [duplicate]

This question already has answers here:
When would you ever use nested locking?
(3 answers)
Closed 11 months ago.
It says here :
While a lock is held, the thread that holds the lock can again acquire and release the lock.
Question. For what purpose can several consecutive locks be used in one thread? Or does it give nothing, but the article says to clarify that inside one thread the code in the second lock will also be executed because the lock is used in the same thread?
I just want to understand the purpose of this information.
Its called recursive locking. It is useful if you have complex paths that may end up trying to lock a resource twice (like in a recursive function). It saves you have to keep track of whether or not you already have a lock.
It is typically implemented as a counter, after the first lock subsequent locks just increment the counter, unlocks decrement, when the count reaches 0 the mutex is released

Using static functions in a asp.net 3.5 website [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am building a ASP.NET webapplication in which I use several classes containing static functions for retreiving database values and such (based on session of user so their results are session specific, not application wide).
These functions can also be called from markup, which makes developing my GUI fast and easy.
Now I am wondering: is this the right way of doing things, or is it better to create a class, containing these functions and create an instance of the class when needed?
What will happen when there are a lot of visitors to this website? Will a visitor have to wait until the function is 'ready' if it's also called by another session? Or will IIS spread the workload over multiple threads?
Or is this just up to personal preferences and one should test what works best?
EDIT AND ADDITIONAL QUESTION:
I'm using code like this:
public class HandyAdminStuff
{
public static string GetClientName(Guid clientId)
{
Client client = new ClientController().GetClientById(clientId);
return client.Name;
}
}
Will the Client and ClientController classes be disposed of after completion of this function? Will the GarbageCollector dispose of them? Or will they continue to 'live' and bulk up memory everytime the function is called?
** Please, I don't need answers like: 'measure instead of asking', I know that. I'd like to get feedback from people who can give a good answer an maybe some pro's or cons, based on their experience. Thank you.
"Will a visitor have to wait until the function is 'ready' if it's also called by another session?"
Yes. It may happen if you have thread safe function body, or you perform some DB operations within transaction that locks DB.
Take a look at these threads:
http://forums.asp.net/t/1933971.aspx?THEORY%20High%20load%20on%20static%20methods%20How%20does%20net%20handle%20this%20situation%20
Does IIS give each connected user a thread?
It would be better to have instance based objects because they can also be easily disposed (connections possibly?) and you wouldn't have to worry about multithreading issues, additional to all the problems "peek" mentioned.
For example, each and every function of your static DAL layer should be atomic. That is, no variables should be shared between calls inside the dal. It is a common mistake in asp.net to think that [TreadStatic] data is safe to be used inside static functions. The only safe pool for storing per request data is the Context.Items pool, everything else is unsafe.
Edit:
I forgot to answer you question regarding IIS threads. Each and every request from your customers will be handled by a different thread. As long as you are not using Session State, concurrent requests from the same user will be also handled concurrently by different threads.
I would not recommend to use static function for retrieving data. This because these static functions will make your code harder to test, harder to maintain, and can't take advantage of any oo principals for design. You will end up with more duplicate code, etc.

What is the measurements for determining If the code is Thread safe or not in .net [duplicate]

This question already has answers here:
Multi Threading [closed]
(5 answers)
Closed 9 years ago.
How can I measure a code if it is thread-safe or not?
may be general guidelines or best practices
I know that the code to be threading safe is to work across threads without doing unpredictable behavior, but that's sometimes become very tricky and hard to do!
I came up with one simple rule, which is probably hard to implement and therefore theoretical in nature. Code is not thread safe if you can inject some Sleep operations to some places in the code and so change the outcome of the code in a significant way. The code is thread safe otherwise (there's no such combination of delays that can change the result of code execution).
Not only your code should be taken into account when considering thread safety, but other parts of the code, the framework, the operating system, the external factors, like disk drives and memory... everything. That is why this "rule of thumb" is mainly theoretical.
I think The best answer would be here
Multi Threading, I couldn't have notice such an answer before writing this question
I think it is better to close is it !
thanks
Edit by 280Z28 (since I can't add a new answer to a closed question)
Thread safety of an algorithm or application is typically measured in terms of the consistency model which it is guaranteed to follow in the presence of multiple threads of execution (or multiple processes for distributed systems). The two most important things to examine are the following.
Are the pre- and post-conditions of individual methods preserved when multiple threads are used? For example, if your method "adds an element to a dynamically-sized list", then one post condition would be that the size of the list increases by 1 as a result of the add method. If your algorithm is thread-safe, then calling the add method 2 times would result in the size increasing by exactly 2, regardless of which threads were used for the add operations. On the other hand, if the algorithm is not thread-safe, then using multiple threads for the 2 calls could result in anything, ranging from correctly adding the 2 items all the way to the possibility of crashing the program entirely.
When changes are made to data used by algorithms in the program, when do those changes become visible to the other threads in the system. This is the consistency model of your code. Consistency models can be very difficult to understand fully so I'll leave the link above as the starting place for your continued learning, along with a note that systems guaranteeing linearizability or sequential consistency are often the easiest to work with, although not necessarily the easiest to create.

C# - Best way to optimize data updates [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
just a simple question on data updating.
Suppose I have a TextBox called txtBox1 and I want to update the value of a string variable called foo.
Which gives the best performance and best to do?
// The lengthier code but will check if the value is the same before updating.
if (foo != txtBox1.Text)
foo = txtBox1.Text;
or
// The shorter code but will update it regardless if it's the same value
foo = txtBox1.Text;
It really depends on what you do with foo variable.
If updating foo involves updating other parts of your application (via data binding for example) then yes, you should only update it when necessary.
Original Answer
Warning: I messed up... this answer applies for the opposite case, that is:
txtBox1.Text = foo
It may depend on what TextBox you are using...
I haven't reviewed all the clases with that name in the .NET framework from Microsoft. But I can tell for System.Windows.Forms.TextBox that the check is done internally, so doing it yourself is a waste. This is probably the case for the others.
New Answer
Note: This is an edit based on the comments. It it taken from granted that the objective is keep track of the modifications of the texbox and that we are working in windows forms or similar dektop forms solution (that may be WinForms, WPF, GTK#, etc..).
IF you need every value...
TextChanged is the way to go if you want a a log or undo feature where you want to offer each value the textbox was in.
Although take note that the event runs in the same thread as that the text was assigned, and that thread ought to be the thread that created the textbox. Meaning that if you cause any kind of lock or do an expensive operation, it will heavily^1 impact the performance of the form, causing it to react slowly because the thread that must update the form is busy in the TextChanged handler.
^1: heavily compared to the alternative presented below.
If you need to do an expensive operation, what you should do is add the values to a ConcurrentQueue<T> (or similar). And then you can have an async^2 operation run in the background that takes the values from it and process them. Make sure to add to the queue the necessary parameters^3, that way the expensive operation can happen in the background.
^2: It doesn't need to be using the async keyword, it can be a ThreadPool, a Timer, a dedicated Thread or something like that.
^3: for example the text, and the time in the case of a log. If have to monitor multiple controls you could also consider using a POCO (Plain Old CLR Object) class or struct to store all the status that need to be kept.
IF you can miss some values...
Using the event
Use the event to update a version number instead of reading the value.
That is, you are going to keep two integer variables:
The current version number that you will increment when there were a change. Use Thead.VolatireWrite for this (there is no need for Interlocked)
The last checked version number that you will update when you read the values from the form (this done from an async operation), and that you will use to verify if there has been any updates recently. Use Interlocked.Exchange to update the value and proceed if the old value is different from the readed one.
Note: Test the case of aritmetic overflow and make sure it wraps MaxValue to MinValue. No, it will not happen often, but that's no excuse.
Again, under the idea that it is ok to miss some values... If you are using a dedicated Thread for this, you may want to use a WaitHandle (ManualResetEvent or AutoResetEvent [and preferably it's slim counterparts]) to have the thread sleep when there hasn't been modifications instead of having it nopping (spin waiting). You will then set the WaitHandle in the event.

A good reason to use lock (this)? [duplicate]

This question already has answers here:
Why is lock(this) {...} bad?
(18 answers)
Closed 9 years ago.
There are many posts, votes and answers indicating using lock (this) is not a recommends pattern (not to mention a bad one).
Have a look at this one, for example.
As I'm trying to investigate this pattern a little bit, and wanted to ask whether anyone someone can think of a scenario in which using lock (this) is actually recommended, or even a must?
Locking on THIS is evil. This means that someone may decide to lock on your instance. This means that your instance will wait until someone else releases it.
Rule of thumb: never lock on this but create a seperate (private) object to lock.
But... The problem is deeper: locking has a purpose, by locking you provide protection on the upper object(s) but it doesn't prevent updating the underlying objects in for instance a collection.
In most cases a lock isn't a need. Read up on the subject is what I suggest.
Multiple questions on SO cover you question. Shouldn't be hard to build an opinion about the motivation to not lock on this.
An example and pointers for further reading can be found on the blog of Phil Haack

Categories