Why does MSDN sample from Threading Tutorial crash? - c#

From sample example 4 of MSDN "Threading Tutorial"
Following code errors out at the line commented with "---errors is here---".
What is wrong?
using System;
using System.Threading;
public class MutexSample
{
static Mutex gM1;
static Mutex gM2;
const int ITERS = 100;
static AutoResetEvent Event1 = new AutoResetEvent(false);
static AutoResetEvent Event2 = new AutoResetEvent(false);
static AutoResetEvent Event3 = new AutoResetEvent(false);
static AutoResetEvent Event4 = new AutoResetEvent(false);
public static void Main(String[] args)
{
Console.WriteLine("Mutex Sample ...");
// Create Mutex initialOwned, with name of "MyMutex".
gM1 = new Mutex(true, "MyMutex");
// Create Mutex initialOwned, with no name.
gM2 = new Mutex(true);
Console.WriteLine(" - Main Owns gM1 and gM2");
AutoResetEvent[] evs = new AutoResetEvent[4];
evs[0] = Event1; // Event for t1
evs[1] = Event2; // Event for t2
evs[2] = Event3; // Event for t3
evs[3] = Event4; // Event for t4
MutexSample tm = new MutexSample();
Thread thread1 = new Thread(new ThreadStart(tm.t1Start));
Thread thread2 = new Thread(new ThreadStart(tm.t2Start));
Thread thread3 = new Thread(new ThreadStart(tm.t3Start));
Thread thread4 = new Thread(new ThreadStart(tm.t4Start));
thread1.Start(); // Does Mutex.WaitAll(Mutex[] of gM1 and gM2)
thread2.Start(); // Does Mutex.WaitOne(Mutex gM1)
thread3.Start(); // Does Mutex.WaitAny(Mutex[] of gM1 and gM2)
thread4.Start(); // Does Mutex.WaitOne(Mutex gM2)
Thread.Sleep(2000);
Console.WriteLine(" - Main releases gM1");
gM1.ReleaseMutex(); // t2 and t3 will end and signal
Thread.Sleep(1000);
Console.WriteLine(" - Main releases gM2");
gM2.ReleaseMutex(); // t1 and t4 will end and signal
// Waiting until all four threads signal that they are done.
WaitHandle.WaitAll(evs);
Console.WriteLine("... Mutex Sample");
}
public void t1Start()
{
Console.WriteLine("t1Start started, Mutex.WaitAll(Mutex[])");
Mutex[] gMs = new Mutex[2];
gMs[0] = gM1; // Create and load an array of Mutex for WaitAll call
gMs[1] = gM2;
Mutex.WaitAll(gMs); // Waits until both gM1 and gM2 are released
Thread.Sleep(2000);
Console.WriteLine("t1Start finished, Mutex.WaitAll(Mutex[]) satisfied");
Event1.Set(); // AutoResetEvent.Set() flagging method is done
}
public void t2Start()
{
Console.WriteLine("t2Start started, gM1.WaitOne( )");
gM1.WaitOne(); // Waits until Mutex gM1 is released ---errors is here---
Console.WriteLine("t2Start finished, gM1.WaitOne( ) satisfied");
Event2.Set(); // AutoResetEvent.Set() flagging method is done
}
public void t3Start()
{
Console.WriteLine("t3Start started, Mutex.WaitAny(Mutex[])");
Mutex[] gMs = new Mutex[2];
gMs[0] = gM1; // Create and load an array of Mutex for WaitAny call
gMs[1] = gM2;
Mutex.WaitAny(gMs); // Waits until either Mutex is released
Console.WriteLine("t3Start finished, Mutex.WaitAny(Mutex[])");
Event3.Set(); // AutoResetEvent.Set() flagging method is done
}
public void t4Start()
{
Console.WriteLine("t4Start started, gM2.WaitOne( )");
gM2.WaitOne(); // Waits until Mutex gM2 is released
Console.WriteLine("t4Start finished, gM2.WaitOne( )");
Event4.Set(); // AutoResetEvent.Set() flagging method is done
}
}

After waiting on a Mutex you have to release it, using
Mutex.ReleaseMutex()
before the threads exits.
fixed t1start - t4start
public void t1Start()
{
Console.WriteLine("t1Start started, Mutex.WaitAll(Mutex[])");
Mutex[] gMs = new Mutex[2];
gMs[0] = gM1; // Create and load an array of Mutex for WaitAll call
gMs[1] = gM2;
Mutex.WaitAll(gMs); // Waits until both gM1 and gM2 are released
Thread.Sleep(2000);
Console.WriteLine("t1Start finished, Mutex.WaitAll(Mutex[]) satisfied");
Event1.Set(); // AutoResetEvent.Set() flagging method is done
gM1.ReleaseMutex();
gM2.ReleaseMutex();
}
public void t2Start()
{
Console.WriteLine("t2Start started, gM1.WaitOne( )");
gM1.WaitOne(); // Waits until Mutex gM1 is released ---errors is here---
Console.WriteLine("t2Start finished, gM1.WaitOne( ) satisfied");
gM1.ReleaseMutex();
Event2.Set(); // AutoResetEvent.Set() flagging method is done
}
public void t3Start()
{
Console.WriteLine("t3Start started, Mutex.WaitAny(Mutex[])");
Mutex[] gMs = new Mutex[2];
gMs[0] = gM1; // Create and load an array of Mutex for WaitAny call
gMs[1] = gM2;
int result = Mutex.WaitAny(gMs); // Waits until either Mutex is released
gMs[result].ReleaseMutex();
Console.WriteLine("t3Start finished, Mutex.WaitAny(Mutex[])"); Event3.Set(); // AutoResetEvent.Set() flagging method is done
}
public void t4Start()
{
Console.WriteLine("t4Start started, gM2.WaitOne( )");
gM2.WaitOne(); // Waits until Mutex gM2 is released
Console.WriteLine("t4Start finished, gM2.WaitOne( )");
Event4.Set(); // AutoResetEvent.Set() flagging method is done
gM2.ReleaseMutex();
}

Related

MultiThreading Async

Why does this code not reach the Console.WriteLine("Other thread is done!"); ? This code is from Pro C# 5.0 and the .NET 4.5 Framework book, pg 717-718.
private static AutoResetEvent waitHandle = new AutoResetEvent(false);
static void Main(string[] args)
{
Console.WriteLine("ID of thread in Main(): {0}", Thread.CurrentThread.ManagedThreadId);
AddParms data = new AddParms(3, 4);
Thread t = new Thread(new ParameterizedThreadStart(Add));
t.Start(data);
waitHandle.WaitOne();
Console.WriteLine("Other thread is done!");
Console.ReadLine();
}
private static void Add(object data)
{
Console.WriteLine("ID of thread in Add(): {0}", Thread.CurrentThread.ManagedThreadId);
AddParms ap = (AddParms)data;
Console.WriteLine("{0} + {1} = {2}", ap.A, ap.B, ap.A + ap.B);
}
waitHandle.WaitOne();
This line causes the execution to stop until the wait handle is set.
The provided code never sets that wait handle, and thus the code blocks indefinitely.

thread start stop c# WinForm

Background:
In C# WinForm, I use several Threads like this
private Thread Thread1;
Thread1 = new Thread(new ThreadStart(DoSomething));
Thread1.Start();
And I want to set a timer to Stop/Kill the Thread1 every hour, and restart a new Thread1 like this:
Abort/Kill Thread1;
Thread1 = new Thread(new ThreadStart(DoSomething));
Thread1.Start();
So How to kill the thread1 and restart a new one without Restart my Winform?
Thank you kindly for your reply. I much appreciated it
You can do so by having a while loop in DoSomething that continues based on a volatile bool. Please see Groo's answer here:
Restarting a thread in .NET (using C#)
Here is a sample.
private void button1_Click(object sender, EventArgs e) {
var i = 0;
Action DoSomething = () => {
while (true) {
(++i).ToString();
Thread.Sleep(100);
}
};
Thread Thread1;
Thread1 = new Thread(new ThreadStart(DoSomething));
Thread1.Start();
Thread.Sleep(1000);
Text = i.ToString();
Thread1.Abort();
Thread1 = new Thread(new ThreadStart(DoSomething));
Thread1.Start();
}
I don't recommend Thread.Abort method.
When possible, design the thread what can stop safety. And use Join method.
private void button2_Click(object sender, EventArgs e) {
// the flag, to stop the thread outside.
var needStop = false;
var i = 0;
Action DoSomething = () => {
while (!needStop) {
(++i).ToString();
Thread.Sleep(100);
}
};
Thread Thread1;
Thread1 = new Thread(new ThreadStart(DoSomething));
Thread1.Start();
Thread.Sleep(1000);
Text = i.ToString();
// change flag to stop.
needStop = true;
// wait until thread stop.
Thread1.Join();
// start new thread.
Thread1 = new Thread(new ThreadStart(DoSomething));
Thread1.Start();
// needStop = true;
// Thread1.Join();
}

Multithreading in C# with Win.Forms control

I'm beginner in C#. And i have problem with threads when i using win.forms. My application freezes. What the problem with this code? I'm using microsoft example from msdn.
Here's my code:
delegate void SetTextCallback(object text);
private void WriteString(object text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(WriteString);
this.Invoke(d, new object[] { text });
}
else
{
for (int i = 0; i <= 1000; i++)
{
this.textBox1.Text = text.ToString();
}
}
}
private void button1_Click(object sender, EventArgs e)
{
Thread th_1 = new Thread(WriteString);
Thread th_2 = new Thread(WriteString);
Thread th_3 = new Thread(WriteString);
Thread th_4 = new Thread(WriteString);
th_1.Priority = ThreadPriority.Highest; // самый высокий
th_2.Priority = ThreadPriority.BelowNormal; // выше среднего
th_3.Priority = ThreadPriority.Normal; // средний
th_4.Priority = ThreadPriority.Lowest; // низкий
th_1.Start("1");
th_2.Start("2");
th_3.Start("3");
th_4.Start("4");
th_1.Join();
th_2.Join();
th_3.Join();
th_4.Join();
}
There is a deadlock - UI thread is waiting for threads to complete with Thread.Join() while the worker threads are trying to send a message to UI using blocking Control.Invoke(). Replacing the Invoke in the thread code by BeginInvoke() will make the deadlock go away
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(WriteString);
// BeginInvoke posts message to UI thread asyncronously
this.BeginInvoke(d, new object[] { text });
}
else
{
this.textBox1.Text = text.ToString();
}
It freezes because of the Join calls. Thread.Join() makes the current thread wait after another one is complete.

Measuring thread running time

public void Foo(IRB inR) {
Stopwatch sw = new Stopwatch();
sw.Start();
System.Threading.Thread theThread = new System.Threading.Thread(delegate() {
if (inR.Ready) {
inR.ABC();
while (!inR.Ready) { Thread.Sleep(100); }
}
mP.CP = false;
});
theThread.Name = "aaabbbccc";
theThread.Start();
}
So, I want use StopWatch measuring the time that "theThread" running. (Actually, I want to measure time from creating of this thread to end of thread.)
I already put stopwatch.start() where I want. But where should I put my stopwatch.stop()?
Thank you.
Why not put the stopwatch code in the thread itself? For example:
public class ThreadTimer
{
private readonly ThreadStart realWork;
public ThreadTimer(ThreadStart realWork)
{
this.realWork = realWork;
}
public void TimeAndExecute()
{
Stopwatch stopwatch = Stopwatch.StartNew();
try
{
realWork();
}
finally
{
stopwatch.Stop();
// Log or whatever here
}
}
}
Then:
ThreadStart work = delegate() {
if (inR.Ready) {
inR.ABC();
while (!inR.Ready) { Thread.Sleep(100); }
}
mP.CP = false;
};
ThreadTimer timer = new ThreadTimer(work);
Thread thread = new Thread(timer.TimeAndExecute);
thread.Start();
Can you put it at the end of your delegate?
You'd have to join the background thread with the running thread if you create the Stopwatch object as a variable local to your function. Or, you can create it outside the function to let the thread run without joining.
public void ConditionPlate(IRB inR)
{
Stopwatch sw = new Stopwatch();
sw.Start();
System.Threading.Thread theThread = new System.Threading.Thread(delegate()
{
if (inR.Ready)
{
inR.ABC();
while (!inR.Ready) { Thread.Sleep(100); }
}
mP.CP = false;
// ********************************
// This will stop the stopwatch.
// ********************************
sw.Stop();
});
theThread.Name = "aaabbbccc";
theThread.Start();
// Wait for the thread to stop (necessary if 'sw' is created here, locally)
theThread.Join();
// gets time required for creation of thread to thread completion.
var elapsed = sw.Elapsed;
}

Wait main thread until other threads not get complete!

I am not using any thread pool. Just creating ThreadArray.The for loop creats the thread but same time main thread continues.... How can I apply wait on main thread until all threads created by for loop not get completed.
Code:
public List<DirInfo> ScanDir()
{
for (int i = 0; i < 5; i++)
{
threadArray[i] = new Thread(delegate()
{
StartScanning(paths);
}
);
threadArray[i].Start();
}
....
List<DirInfo> listInfo = new List<DirInfo>();
...
...
....
return listInfo
}
Code:
public List<ServerDataInformation> ScanParallel()
{
var appConfigData = ReadAppConfig();
if (appConfigData == null)
{
EventPublisher.NotifyApplication("Error in appconfig File");
return null;
}
int pathCount = appConfigData.Length;
string serverPath;
string serverName;
var waitHandles = new WaitHandle[pathCount];
Thread[] threadArray = new Thread[pathCount];
for (int i = 0; i < pathCount; i++)
{
// waitHandles[i] = new AutoResetEvent(false);
var handle = new EventWaitHandle(false, EventResetMode.ManualReset);
serverPath = appConfigData[i].Split(',').First();
serverName = appConfigData[i].Split(',').Last();
var threadSplit = new Thread(() =>
{
ScanProcess(serverPath, serverName); --------->> not executing as many times as I increment
handle.Set();
});
waitHandles[i] = handle;
threadSplit.Start();
}
//if (WaitHandle.WaitAll(waitHandles))
//{
// return serverDataInfoList;
// // EventPublisher.NotifyApplication("timeout!!");
//}
return serverDataInfoList;
}
Here 4 is the lenght of pathCount but
ScanProcess(serverPath, serverName);
is not executing 4 time with different values. It is executing 4 times but with same vaues
You could use wait handles:
var waitHandles = new ManualResetEvent[10];
for (int i = 0; i < 10; i++)
{
waitHandles[i] = new ManualResetEvent(false);
new Thread(waitHandle =>
{
// TODO: Do some processing...
// signal the corresponding wait handle
// ideally wrap the processing in a try/finally
// to ensure that the handle has been signaled
(waitHandle as ManualResetEvent).Set();
}).Start(waitHandles[i]);
}
// wait for all handles to be signaled => this will block the main
// thread until all the handles have been signaled (calling .Set on them)
// which would indicate that the background threads have finished
// We also define a 30s timeout to avoid blocking forever
if (!WaitHandle.WaitAll(waitHandles, TimeSpan.FromSeconds(30)))
{
// timeout
}
Have you tried the .Net 4 Task Parallel Library
MSDN Task Parallel Library
Task[] tasks = new Task[3]
{
Task.Factory.StartNew(() => MethodA()),
Task.Factory.StartNew(() => MethodB()),
Task.Factory.StartNew(() => MethodC())
};
//Block until all tasks complete.
Task.WaitAll(tasks);
// Continue on this thread...
Associate each thread with a waithandle, then use WaitHandle.WaitAll.If you start thread by async delegate call instead of a new thread object, it will give you the async result as waithandle.
for(int i = 0;i<10;i++)
{
thread = new Thread(new ThreadStart(Get_CR_Information));
thread.IsBackground = true;
thread.Start();
WaitHandle[] AWait = new WaitHandle[] { new AutoResetEvent(false) };
while ( thread.IsAlive)
{
WaitHandle.WaitAny(AWait, 50, false);
System.Windows.Forms.Application.DoEvents();
}
}
try this it will work fine...
Try using CountdownEvent synchronization primitive, Below link contains an example.
https://msdn.microsoft.com/en-us/library/dd997365(v=vs.110).aspx

Categories

Resources