Why should i pass object to lock keyword while synchronizing [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
object c = new object();
lock(c)
{
}
Why should i pass object to lock keyword while synchronizing above code.If i pass also where will it be used.I know it is used for acquiring a lock on that object.but i wanted to know how can we acquire lock on object in depth.How does the thread release the lock on the object we pass in lock keyword.

lock statement is a syntactic sugar of using Monitor approach to thread synchronization. Monitor represents an exclusive lock on some resource, and in .NET a resource is an object.
Why you need to give an object reference to a Monitor? Well, because you want to synchronize the access to the whole object in a multi-threaded environment.
How does the thread release the lock on the object we pass in lock
keyword?
Think about lock as follows:
Monitor.Enter(obj);
try
{
// This would be the code inside the "lock" block
}
finally
{
if(Monitor.IsEntered(obj))
Monitor.Exit(obj); // <-- This is how a Monitor releases the lock
}

you don't need to restrict your locking to an Object object, you could lock a Dictionary object for example, to prevent other threads from adding or deleting from the collection.
or
if you don't want to use the lock keyword, you could use [MethodImpl(MethodImplOptions.Synchronized)]
eg.
[MethodImpl(MethodImplOptions.Synchronized)]
static void mySynchronisedTask()
{
//do things that i want to be synchronised
Console.WriteLine("before sync task");
Thread.Sleep(5000);
Console.WriteLine("after sync task");
}

Related

How to prevent method from running in multiple instances [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 months ago.
Improve this question
I created a method that polls a database. If two instances of the exe are run, I wouldn't want both instances to be able to run the polling method simultaneously.
How might I best ensure the polling method is only ever active in one thread (regardless of which process owns the thread), and that if another thread calls it it will throw an exception?
I would use Mutex to avoid multiple access to the same recourses.
Here you have a brief piece of code to achieve this
Mutex mutex;
private void StartPolling()
{
mutex = new Mutex(true, "same_name_in_here", out bool createdNew);
if (!createdNew) { throw new Exception("Polling running in other process"); }
//now StartPolling can not be called from other processes
//polling stuff in here
}
private void StopPolling()
{
mutex?.Dispose();
mutex = null;
//now StartPolling can be called from other processes
//Stop any polling operation
}

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

Is waiting a thread to be alive with a loop good practice? [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 6 years ago.
Improve this question
Do we really have to do this?
// Loop until worker thread activates.
while (!workerThread.IsAlive);
Wouldn't it be better to just use a ManualResetEvent (or else) at the start of the thread's function?
Edit 1:
Perhaps in the MSDN example context it would be "appropiate":
// Start the worker thread.
workerThread.Start();
Console.WriteLine("main thread: Starting worker thread...");
 
// Loop until worker thread activates.
while (!workerThread.IsAlive);
Otherwise this just feels like an awful code smell.
Source: http://msdn.microsoft.com/en-US/library/7a2f3ay4(v=vs.80).aspx
Please ignore the MSDN example, it's horrible and senseless. In particular, the spin waiting on IsAlive makes no sense because there is no way for the thread to be terminated "before it has a chance to execute", as the MSDN says. The thread is free not to check the flag you set for requesting termination until it is ready. Spin-waiting on IsAlive never makes sense -- use Thread.Join() to wait on exit, and events (or monitors) to wait for other states.
Good practice is to use the Task-based Asynchronous Pattern (TAP)
Use Task.Run like this,
public async Task DoStuff(CancellationToken token)
{
await Task.Run(
() => Console.WriteLine("Stuff"),
token)
}
or just,
Task.Run(() => Console.WriteLine("Stuff")).Wait();
There is no built-in infrastructure to wait for thread to start, because in most cases this should not be important. We must wait for thread to finish always, but let it do about its business in the mean time.
You probably even don't want to wait for thread to start. You probably want for thread to activate some of its functionality, and in general case there could me more than one of those functionalities. No built-in system can cater for this, so you have to roll your own synchronization.
Just have some event that is created when the thread is created, but is raised in the thread run code. When you create and start the thread wait on this event and that's it.

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

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.

Does construct a new object cause Memory leak [closed]

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
Does this method use plenty of my memory resources?
Private MyWorkerClass worker;
Private Thread myWorkerThread;
//private Thread myWorkerThread= new Thread(worker.doThisWork); // i cant do this, because i cant restart the thread when i construct it here.
public void IwantMyWorkDosomething(){
myWorkerThread= new Thread(worker.doThisWork);
myWorkerThread.start();
myWorkerThread.stopWorking(); // stop my worker class thread running;
}
public void main(){
this.IwantMyWorkDosomething();
this.IwantMyWorkDosomething();
this.IwantMyWorkDosomething();
this.IwantMyWorkDosomething();
this.IwantMyWorkDosomething();
}
my Code is working, but i am not sure whether it gonna crash my program if i run the method 1000 times.
Constructing a thread object is cheap. Also, re-constructing a new one is cheap. The garbage collector will free the unused resources, you just need to make sure you're not unnessecarilly keeping references to finished thread objects.
What could become a resource problem is only when you try to run thousands of threads at the same time. But even then, it's not the memory that will usually cause the bottleneck but the CPU and the task scheduler (i.e the tasks will start to run slower than exected).

Categories