AutoresetEvent and Singleton issue - c#

Can someone please tell me what is wrong with the following code? Ideally it should start a thread first and then wait for the set event. Instead of that it does not start the thread and just get stuck on WaitOne().
I am curious to know what happened to the thread and why?
class Program
{
static void Main(string[] args)
{
Testing t = Testing.Instance;
Console.Read();
}
}
class Testing
{
private static AutoResetEvent evt = new AutoResetEvent(false);
public static Testing Instance = new Testing();
private Testing()
{
Create();
evt.WaitOne();
Console.WriteLine("out");
}
private void Create()
{
Console.WriteLine("Starting thread");
new Thread(Print).Start();
}
private void Print()
{
Console.WriteLine("started");
evt.Set();
}
}
EDIT:
So far, the description provided by #BrokenGlass makes sense. but changing the code to the following code allows another thread can access the instance methods without constructor being completed.(Suggested by #NicoSchertler).
private static Testing _Instance;
public static Testing Instance
{
get
{
if (_Instance == null)
_Instance = new Testing();
return _Instance;
}
}

I suspect the root cause of this behavior is that the spawned thread cannot access the Print method until the constructor has finished executing - but the constructor never finishes executing because it is waiting on the signal that is triggered only from the Print method.
Replacing the evt.WaitOne() with a long Thread.Sleep() call confirms the same behavior - the constructor must finish running before any instance method of the object may execute from another thread.

The problem is that the second thread is created too early. I'm not sure why, but when started before the main program starts, it will not execute.
You should use the singleton pattern in its original version. This will work.
private static Testing _Instance;
public static Testing Instance
{
get
{
if (_Instance == null)
_Instance = new Testing();
return _Instance;
}
}
Additionally, you should not make the evt variable static. The instance variable should be the only static member of a singleton class in most cases.

My guess would be an issue with the relative timing of the static field initialization. Try initializing evt in the constructor of Testing instead:
private static AutoResetEvent evt;
public static Testing Instance = new Testing();
private Testing()
{
evt = new AutoResetEvent(false);
Create();
evt.WaitOne();
Console.WriteLine("out");
}
I should note this is really just a guess- I'd have thought this code would work fine.

Related

SynchronizationAttribute.SUPPORTED creates synchronization content

According to article class below is not thread safe:
I have code which gets into lock while according to my understanding has different synchronization content:
[Synchronization]
public class Deadlock : ContextBoundObject
{
public DeadLock Other;
public void Demo() { Thread.Sleep (1000); Other.Hello(); }
void Hello() { Console.WriteLine ("hello"); }
}
public class Test
{
static void Main()
{
Deadlock dead1 = new Deadlock();
Deadlock dead2 = new Deadlock();
dead1.Other = dead2;
dead2.Other = dead1;
new Thread (dead1.Demo).Start();
dead2.Demo();
}
}
It does and it is fine. But I decided to play with synchronization attributes by setting:
[Synchronization(SynchronizationAttribute.SUPPORTED)]
SUPPORTED means :
Joins the existing synchronization context if instantiated from
another synchronized object, otherwise remains unsynchronized
Since console application has no synchronization content I expect both object will have no synchronization object and should not get into deadlock. But I still have deadlock. Why?
Further have removed [Synchronization] attribute at all. Still have deadlock. What influence makes [Synchronization] attribute to object?
Here you are creating circular dependency between thread , that might lead you to stackoverflow exception , as you are not catching excpetion here you are might not able to view it. I suggest you make use of UnObservedExcpetion handler that will give you excpetion or try to handle excpetion in that same function by putting try, catch block.
To avoid this kind of situation you better make use of AutoResetEvent. below is sample code for the same.
public class MyThreadTest
{
static readonly AutoResetEvent thread1Step = new AutoResetEvent(false);
static readonly AutoResetEvent thread2Step = new AutoResetEvent(true);
void DisplayThread1()
{
while (true)
{
thread2Step.WaitOne();
Console.WriteLine("Display Thread 1");
Thread.Sleep(1000);
thread1Step.Set();
}
}
void DisplayThread2()
{
while (true)
{
thread1Step.WaitOne();
Console.WriteLine("Display Thread 2");
Thread.Sleep(1000);
thread2Step.Set();
}
}
void CreateThreads()
{
// construct two threads for our demonstration;
Thread thread1 = new Thread(new ThreadStart(DisplayThread1));
Thread thread2 = new Thread(new ThreadStart(DisplayThread2));
// start them
thread1.Start();
thread2.Start();
}
public static void Main()
{
MyThreadTest StartMultiThreads = new MyThreadTest();
StartMultiThreads.CreateThreads();
}
}

New thread in singleton never finished

I have simple singleton class:
namespace TestApp
{
public class MySingleton
{
static MySingleton()
{
}
private static readonly MySingleton instance = new MySingleton();
private bool threadFinished = false;
public bool IsReady = false;
private MySingleton()
{
Thread t = new Thread(MyAction);
t.Start();
while (!threadFinished)
Thread.Sleep(10);
}
public static MySingleton Instance
{
get { return instance; }
}
private void MyAction()
{
threadFinished = true;
}
}
}
When I'm trying instatiate this by:
var ir = MySingleton.Instance.IsReady;
it never ends - the while loop is infinite. Why? And how to run backround thread in singleton at constructor?
You're deadlocking. You're not allowed to call any methods from another thread before the static constructor is executed. Static constructor includes the static field initalizers too.
Since you're blocking the calling thread with a while loop, static field initialization will not complete and the new thread will neither be permitted to execute MyAction either.
Your code is almost identical to this code where Eric demonstrates the deadlock.
And to quote eric's comment from same answer why does it deadlock:
#Lieven: The static constructor must run no more than once and it
must run before the first call to any static method in the class. Main
is a static method, so the main thread calls the static ctor. To
ensure it only runs once, the CLR takes out a lock that is not
released until the static ctor finishes. When the ctor starts a new
thread, that thread also calls a static method, so the CLR tries to
take the lock to see if it needs to run the ctor. The main thread
meanwhile "joins" the blocked thread, and now we have our deadlock. –
Eric Lippert Jan 17 '12 at 14:28
To answer your question; Don't do that. You gain nothing by starting a thread and waiting for it. Just simply run the method synchronously.
This works. I am not a Singleton expert - if this violates any rules, someone please point it out. But this gets around the deadlock. I copied your code into a console app, if you're using it elsewhere, adjust appropriately.
namespace TestApp
{
class Program
{
static void Main(string[] args)
{
while (!MySingleton.Instance.IsReady)
Thread.Sleep(100);
Console.WriteLine("Done");
Console.Read();
}
}
public class MySingleton
{
static MySingleton()
{
}
private static readonly MySingleton instance = new MySingleton();
private static bool threadFinished = false;
public bool IsReady
{
get { return threadFinished; }
}
private MySingleton()
{
Thread t = new Thread(new ThreadStart(MyAction));
t.Start();
}
public static MySingleton Instance
{
get { return instance; }
}
static void MyAction()
{
threadFinished = true;
}
}
Have a look at the lock statement when you create an instance of your singleton to make it thread safe.
An example of how to use it in the singleton pattern can be found here: http://www.dofactory.com/net/singleton-design-pattern

Do I need to use locks when simply assigning variables?

When multithreading I know that I need to lock variables if doing things like adding and item to a list etc or I would get a cross thread exception. But do I need to lock them when just assigning variables? I don't mind about if a thread getting an old instance of the variable - I just don't want it to error. Here is an example of what I mean:
public void Run()
{
var thread1 = new Thread(new ThreadStart(Test));
var thread2 = new Thread(new ThreadStart(Test));
thread1.Start();
thread2.Start();
}
private static int _test;
private void Test()
{
while (true)
{
_test += 1;
}
}
If you're just assigning an int, then no. But here you're not just assigning. You're incrementing. So you need some kind of synchronization.
In you want to increment, use Interlocked.Increment:
Interlocked.Increment(ref _test);
Running the code should give you your answer... instead of while(true) write for(i=1;1<1e6;i++) , write the result to screen and run it.
You'll see it does not add up to 2e6, but rather something around 1.2e6. So yes, you need to lock if you want to get out 2e6.
Don't just hypothesize, after that always test and assert.
You have to remember the thread could also be looking at a stale copy, by locking you assure that the version of the variable you are looking at is being refreshed
When I first started coding and thought that maybe I don't need the freshest copy of the variable I would get stuck in infinite loops because I assume the variable would be updated eventually, but if the variable was cached then it would never update
I included examples with brief descriptions, don't worry about the way the thread is started, that is not relevant
private static bool _continueLoop = true;
private static readonly object _continueLoopLock = new object();
private static void StopLoop()
{
lock(_continueLoopLock)
_continueLoop = false;
}
private static void ThreadALoopWillGetStales()
{
while(_continueLoop)
{
//do stuff
//this is not guaranteed to end
}
}
private static void ThreadALoopEventuallyCorrect()
{
while(true)
{
bool doContinue;
lock(_continueLoopLock)
doContinue = _continueLoop;
if(!doContinue)
break;
//do stuff
//this will sometimes result in a stale value
//but will eventually be correct
}
}
private static void ThreadALoopAlwaysCorrect()
{
while(true)
{
bool doContinue;
lock(_continueLoopLock)
if(!_continueLoop)
break;
//do stuff
//this will always be correct
}
}
private static void ThreadALoopPossibleDeadlocked()
{
lock(_continueLoopLock)
while(_continueLoop)
{
//if you only modify "_continueLoop"
//after Acquiring "_continueLoopLock"
//this will cause a deadlock
}
}
private static void StartThreadALoop()
{
ThreadPool.QueueUserWorkItem ((o)=>{ThreadALoopWillGetStales();});
}
private static void StartEndTheLoop()
{
ThreadPool.QueueUserWorkItem((o)=>
{
//do stuff
StopLoop();
});
}
public static void Main(string[] args)
{
StartThreadALoop();
StartEndTheLoop();
}
when you start the loop there is a chance that you will continue to get a stale copy of the variable, that is why you do need some sort of synchronization when accessing a across multiple threads

WaitForm management in nested calls

I have a a wait form FormWait (long running task notification), that has ShowMessage(string message) function.
Often happens in code:
public RootCall()
{
FormWait.ShowMessage("Begin long task 1...");
ChildCall();
FormWait.CloseForm();
}
public ChildCall()
{
FormWait.ShowMessage("Begin long task 2...");
// some code here
FormWait.CloseForm();
}
FormWait on root shows the message to the user, but before closing it on root level, there is another ShowMessage of child and CloseForm of child.
I have a couple of solutions to resolve this:
Like in code provided the methods are static and operate on one static System.Windows.Forms.Form instance. On every ShowMessage there is a static variable that increments and on every CloseForm it decrements. So by looking on that variable I can understand if I really need to close the form (if I'm or not on root level), or its just a nested CloseForm call. And on every ShowMessage new string just updated on already visible form.
For every new ShowMessage call create new instance of the form, but this is really wired to see. So almost sure I will not pick this solution.
Any ideas, how can I manage WaitForm (form that signals to user about long running tasks) in case of nested calls, by making also the developer life easier.?
The Stack<> class is the natural fit for this:
public partial class WaitForm : Form {
private WaitForm() {
InitializeComponent();
}
private static WaitForm instance;
private static Stack<string> messages = new Stack<string>();
public static void ShowMessage(string message) {
if (instance == null) {
instance = new WaitForm();
instance.FormClosed += delegate { instance = null; };
instance.Show();
}
messages.Push(message);
instance.lblMessage.Text = message;
instance.Update();
}
public static void CloseForm() {
messages.Pop();
if (instance != null) {
if (messages.Count == 0) instance.Close();
else instance.lblMessage.Text = messages.Peek();
}
}
}
Don't forget to put the CloseForm() call in a finally block so this is all exception safe.

Usage of Mutex in c#

I am a bit new in threading in c# and on general,
in my program I am using mutex to allow only 1 thread getting inside a critical section and for unknown reason with doing some cw prints I can see that more than 1 thread is getting inside my critical section and this is my code :
Mutex m = new Mutex();
m.WaitOne();
<C.S> // critical section here
m.ReleaseMutex();
I would very much like to know if I am doing a mistake here thanks in advance for your kind help.
EDIT:
My code include classes so it basically looks more like this:
public class test
{
private mutex m;
public test()
{
m = new mutex();
}
public func()
{
m.WaitOne();
<C.S> // critical section here
m.ReleaseMutex();
}
}
The problem here is that all your callers are using a different mutex; you need the locking object to be shared, usually by making it a field. For example, and switching to a simpler lock metaphor:
private readonly object syncLock = new object();
public void ThreadSafeMethod() {
lock(syncLock) {
/* critical code */
}
}
or using the mutex:
private readonly Mutex m = new Mutex();
public void ThreadSafeMethod() {
m.WaitOne();
try {
/* critical code */
} finally {
m.ReleaseMutex();
}
}
It looks like you give each Thread its own Mutex. That won't work.
And a Mutex is overkill in most situations. You only need:
private static object syncLock = new object(); // just 1 instance
....
lock(syncLock)
{
// critical section
}
This pattern does no locking at all. Every thread creates a new Mutex object and immediately owns the lock for it. Other threads create and use a new Mutex itself.
Consider using a regular lock()!
lock(_lockobject) {
// do inside what needs to be done - executed on a single thread only
}
where _lockobject is a simple private variable in your class:
private object _lockobject;
Edit: thanks to the commenters! Situations exist, where lock(this) can be dangerous. So I removed that.
Mutex use to identify run app instance.
using (Mutex mutex = new Mutex(true, "app name", out createdNew))
{
if (createdNew)//check app is already run
{
KillOthers();
StartApp();
}
else
{
MessageBox.Show("Another instance already running!");
}
}
May i add a correction to the accepted answer?
private readonly Mutex m = new Mutex();
public void ThreadSafeMethod() {
while(!m.WaitOne()){}
try {
/* critical code */
} finally {
m.ReleaseMutex();
}
}

Categories