calling a static parameter from one public class to another - c#

I'm trying to write a multi-threaded app , and I need to use Monitoer.Enter/Exit/Wait/Pulse
I've created a Lock object and used it in its own class like that
public partial class domain
/*I dont sure this is the good practice way to mange DDD Layers (if anybody have a comment about it)*/
{
Public class Peer2PeerCom
{
public static readonly object locker = new object();
//other stuff here
//...
//somwhere here
Monitor.Pulse(locker);
}
}
in the other class I want/need to use the locker like that
public class Control
{
public domain.Peer2PeerCom Dom_P2PCom = new domain.Peer2PeerCom();
internal void connection ( int port , string IpAdress)
{
Monitor.Enter(Dom_P2PCom.locker);
//do stuff here
Monitor.wait(Dom_P2PCom.locker);
//..
Monitor.Exit(Dom_P2PCom.locker);
}
}
But when I try I cannot recognize the locker , I think it is because it is static but I dont understand how to correct it without making the entire class static

You're trying to access a static member via a reference. That doesn't work in C#, fortunately - it can lead to very misleading code where it's allowed, e.g. in Java.
Instead, you should use the name of the class to access a static member:
lock (domain.Peer2PeerCom.locker)
{
...
// This should probably be in a while loop...
Monitor.Wait(domain.Peer2PeerCom.locker);
}
(I've used lock rather than explicitly calling Monitor.Enter and Monitor.Exit - it's more idiomatic, and easier to get right - in the code you've given, any exception in the code after entering the monitor would have cause the monitor to be "leaked" - you wouldn't have exited it.)
In general, I'd strongly recommend against using a public static field for a shared lock like this. It makes it much harder to reason about what's using the lock than if it's private within a class. (I'd recommend against public fields in general, along with underscores in class names, classes which are nested for no particular reason, and a class name of domain, too...)

Related

Are Static Fields thread Safe

We have a Static field in a abstract class
ABSTRACT CLASS :-
public abstract class BaseController
{
private static string a;
private static string b;
protected abstract SomeArray[] DoSomeThing();
}
And a derived class
public class Controller1:BaseController
{
protected override SomeArray[] DoSomthing()
{
//////
In this method we are setting the static variables with different values
}
}
We also have a class which is starting threads
public class SomeClass
{
public SomeClass()
{
\\ we are setting the controller we want to call, i mean to decide which base class to call
}
public void Run()
{
Thread t = new Thread(StartThread);
t.Start();
}
public void StartThread()
{
_controller.DoSomeThing();
}
}
All the above service is in a WCF service, and the same client tries to call multiple times which means we have multiple threads running at the same time, we have seen issues where the static variable which we are setting and using that for some DB update process is sometimes having wrong values
I have read some blogs which says static fields are not thread safe, Can some body please help me understand what could be going wrrong in our code and why we are having some incorrect values passed to the DB.
By definition, a static field or member is shared among all instances of that class, only one instance of that field or member exisits; thus, it is not thread safe.
You have two options, either to synchronize the access (basically, using Monitor class) to that field or to use the ThreadStaticAttribute on that field.
However, i advice to reorganize your class hierarchy so that each class has its own instance of the field or member.
Please note that if there are multiple threads working on the same instance of the class Controller, then we go back to the same problem and you should synchronize access to that instance field.
Good Luck

Lock on an object and change its field. Does it work?

If I write a class like this:
public class LockBool
{
public bool validity = true;
}
And then I lock on such an object and change its validity field:
LockBool lockObj = GetTheLockObject();
lock(lockObj)
{
//release some resources
lockObj.validity = false;
}
So if another thread locks on the same object, it can read the validity for flow control.
lock(lockObj)
{
if(!validity)
return;
//do something here
}
Does it work as I expect, without throwing exception?
(If it works but it's bad practice, I also would like to know the details. Thanks!)
P.S.: The reason I tried to use the type with a bool field is to create variable number of lock objects. And it seems difficult to prevent other threads from acquiring the lock after I release resources. So a bool field can tell a thread if this lock is still valid, or it should be garbage-collected.
Please read this article.
using this kind of locking is discouraged, usually you should define a simple object varibale like
private static readonly object _lock;
with this kind of lock object you can sync between instances of your class (because it is static and shared between all instances) and no one can change its value (because it is readonly) and no one can use a lock on it from outside of class and make things go wrong (because it is private)
and if you want to just make the object thread safe (not all objects that are instantiated) you can remove the static and just use as many private object as you should.
UPDATE base on your comment
you can define a class like this
public class LockWrapper<T>
{
public T InsideClass { get; set; }
public readonly object _lock;
}
then use this when you need multiple instance of some class and want to lock on them separately

Lock code section in c#

My question may sound like many others here but it has a flavor I didn't find.
I am trying to understand the following logic
A generic object
public class GenericClass
{
public static void DoSomething(Object lockObj)
{
lock(lockObj)
{
// do something here
}
}
}
Class A
internal class A
{
private static _aLock = new Object();
public void Do_A_Thing()
{
GenericClass.DoSomething(_aLock);
}
}
Class B
internal class B
{
private static _bLock = new Object();
public void Do_B_Thing()
{
GenericClass.DoSomething(_bLock);
}
}
I just hope to confirm if my explanation is correct:
If multiple threads of class "A" will attempt simultaneously access code in "genericClass" method "DoSomething", this method will be locked to all but one instance of class "A". But a single instance of class "B" will be able to proceed with execution any time. If class "B" will also have multiple instances execute, they will not interfere with class "A" locks.
Is this correct based on what you see above?
Yes, your description sounds correct. It is perhaps a little unusual to pass the lock object in, but it'll work fine. The only change I would suggest is to make the static fields readonly so you can't accidentally change the value to a different object reference.
Your conclusion is correct but it is not a good practice to pass locked object around. I suggest to put the lock inside class A and B respectively.
I suggest to write:
internal class A
{
private static readonly _aLock = new Object();
public void Do_A_Thing()
{
lock (_aLock)
{
GenericClass.DoSomething();
}
}
}
Do you have a specific reason to put the lock in another class? Maybe you can solve your problem in a different way?
Also keep in mind that in some conditions, maybe it is not your case, you can have a deadlock if class A and B call each other (A->B->A).
Yes, that is correct. The locks in A and the locks in B are completely unaware of each other. The code will only be blocked when there is another thread locking it with the same object as identifier.
If you are using generics, then something like
public class MyGadget<T>
{
static readonly SyncRoot = new object() ;
public T SynchronizedMethod()
{
lock ( SyncRoot )
{
SynchronizedMethodGuts() ;
}
}
}
should do what you want because MyGadget<Foo> and MyGadget<Bar> are different classes: they each have their own, different SyncRoot field.

Use an anonymous method to avoid creating a single-use object?

I'm trying to refactor a method that parses through a file. To support files of arbitrary size, the method using a chunking approach with a fixed buffer.
public int Parse()
{
// Get the initial chunk of data
ReadNextChunk();
while (lengthOfDataInBuffer > 0)
{
[parse through contents of buffer]
if (buffer_is_about_to_underflow)
ReadNextChunk();
}
return result;
}
The pseudo code above is part of the only public non-static method in a class (other than the constructor). The class only exists to encapsulate the state that must be tracked while parsing through a file. Further, once this method has been called on the class, it can't/shouldn't be called again. So the usage pattern looks like this:
var obj = new MyClass(filenameToParse);
var result = obj.Parse();
// Never use 'obj' instance again after this.
This bugs me for some reason. I could make the MyClass constructor private, change Parse to a static method, and have the Parse method new up an instance of Parse scoped to the method. That would yield a usage pattern like the following:
var result = MyClass.Parse(filenameToParse);
MyClass isn't a static class though; I still have to create a local instance in the Parse method.
Since this class only has two methods; Parse and (private) ReadNextChunk, I'm wondering if it might not be cleaner to write Parse as a single static method by embedding the ReadNextChunk logic within Parse as an anonymous method. The rest of the state could be tracked as local variables instead of member variables.
Of course, I could accomplish something similar by making ReadNextChunk a static method, and then passing all of the context in, but I remember that anon methods had access to the outer scope.
Is this weird and ugly, or a reasonable approach?
This maybe suitable more to code review.
However, these are my comments about your design:
I don't think it will matter much about obj instance only used once. If you bugged with it, there are 2 ways to trick it:
Use of another method such as:
public int Parse()
{
var obj = new MyClass(filenameToParse);
return obj.Parse();
}
Make the MyClass implement IDisposable and wrap it in using statement. I don't recommend this since usually IDisposable has logic in their Dispose() method
I think it is better to make your MyClass accept parameter in Parse to Parse(string fileNameToParse). It will make MyClass as a service class, make it stateless, reusable and injectable.
Regarding impact to static class. First it add coupling between your consumer and MyClass. Sometimes if you want to test / unit test the consumer without using the MyClass parser, it will be hard / impossible to mock the MyClass into something you want.
All you need is a static parse method that creates an instance, much like what you suggest in your question
public class MyClass
{
// your existing code.... but make the members and constructor private.
public static int Parse(string filenameToParse)
{
return new MyClass(filenameToParse).Parse();
}
}
then
just use it like you suggest...
var result = MyClass.Parse(filenameToParse);
MyClass isn't a static class though; I still have to create a local
instance in the Parse method.
You don't need a static class to be able to leverage static methods. For example this works fine:
public class MyClass
{
public static string DoStuff(string input)
{
Console.WriteLine("Did stuff: " + input);
return "Did stuff";
}
}
public class Host
{
public void Main()
{
MyClass.DoStuff("something");
}
}

What is a simple, thread safe assignment pattern in C# for issuing unique counter values?

I am not an expert on multi-threading in C#; I want to be sure to prevent a race condition that would be a hard surely be a difficult to trigger in testing, while also being nearly impossible to debug. The requirement (my application is a utility class to be used in a possibly multi-threaded HTTP server, not using IIS or ASP.NET) is that each instance of a class have a unique identifier for that instance.
I would rather not use heavy-weight GUIDs to avoid the issue, due to their serialized length, as in an HTML representation.
My question is this: is the simple pattern to set the Unique value in the Widget class below a good pattern for this rquirement? Is there a better, safer pattern that is hopefully not to burdensome to implement?
public abstract class Widget : Node
{
private static int UniqueCount = 0;
private static object _lock = new object();
protected int Unique { private set; get; }
protected Widget() : base()
{
// There could be a subtle race condition if this is not thread-safe
// if it is used with a multi-threaded web server
lock (_lock)
{
UniqueCount += 1;
Unique = UniqueCount;
}
}
}
From this answer:
If you're looking to implement the property in such a way that DoneCounter = DoneCounter + 1 is guaranteed not to be subject to race conditions, it can't be done in the property's implementation. That operation is not atomic, it actually three distinct steps:
Retrieve the value of DoneCounter.
Add 1
Store the result in DoneCounter.
You have to guard against the possibility that a context switch could happen in between any of those steps. Locking inside the getter or setter won't help, because that locks scope exists entirely within one of the steps (either 1 or 2). If you want to make sure all three steps happen together without being interrupted, then your synchronization has to cover all three steps. Which means it has to happen in a context that contains all three of them. That's probably going to end up being code that does not belong to whatever class contains the DoneCounter property.
It is the responsibility of the person using your object to take care of thread safety. In general, no class that has read/write fields or properties can be made "thread-safe" in this manner. However, if you can change the class's interface so that setters aren't necessary, then it is possible to make it more thread-safe. For example, if you know that DoneCounter only increments and decrements, then you could re-implement it like so:
private int _doneCounter;
public int DoneCounter { get { return _doneCounter; } }
public void IncrementDoneCounter() { Interlocked.Increment(ref _doneCounter); }
public void DecrementDoneCounter() { Interlocked.Decrement(ref _doneCounter); }
As mentioned, the += (and related) operations are not threadsafe. When doing simple number increments, just use Interlocked.Increment; it will return the old value and is fully threadsafe:
public abstract class Widget : Node
{
private static int UniqueCount = 0;
protected int Unique { private set; get; }
protected Widget() : base()
{
Unique = Interlocked.Increment(ref UniqueCount);
}
}

Categories