Introduction
While working on a side project for my job, I came across a problem in queueing up a set of threaded commands running at the command-prompt level and producing output into a textbox. I needed the commands to run sequentially, rather than concurrently, so my output wouldn't be overlapped with different thread outputs.
Code
<span class="cs-comment"><span class="cs-comment"><span class="cs-comment">
<span class="cs-keyword">using</span> System.Threading;
<span class="cs-comment">// Thread variable</span>
<span class="cs-keyword">private</span> Thread cmdThread;
<span class="cs-comment">// Sample function to implement the wait and queued thread</span>
<span class="cs-keyword">void</span> startThread()
{
<span class="cs-keyword">try</span>{
waitOnThread(); <span class="cs-comment">//force thread wait if other thread is active</span>
ThreadStart threadstart = <span class="cs-keyword">new</span> ThreadStart(threadedFunction());
cmdThread = <span class="cs-keyword">new</span> Thread(threadstart);
cmdThread.Start();
}
<span class="cs-keyword">catch</span>
{
}
}
<span class="cs-comment">// Sample function to load the threaded event</span>
<span class="cs-keyword">void</span> threadedFunction()
{
<span class="cs-comment">//Put your threaded event content here</span>
}
<span class="cs-comment">// Wait on any running thread</span>
<span class="cs-keyword">void</span> waitOnThread()
{
<span class="cs-keyword">try</span>{
<span class="cs-comment">//Update display if needed (indicate wait is going to occur)</span>
<span class="cs-comment">//UPDATE GUI</span>
<span class="cs-comment">//REFRESH GUI</span>
<span class="cs-comment">// Queue thread: do not attempt Join if there is no active thread</span>
<span class="cs-keyword">if</span>(cmdThread != <span class="cs-keyword">null</span>)
<span class="cs-keyword">if</span>(cmdThread.IsAlive == <span class="cs-keyword">true</span>){
cmdThread.Join();
}
<span class="cs-comment">//Update display if needed (indicate wait is complete)</span>
<span class="cs-comment">//UPDATE GUI</span>
<span class="cs-comment">//REFRESH GUI</span>
}
<span class="cs-keyword">catch</span>
{
}
}
Points of Interest
1. This whole procedure is contingent on the existence of the cmdThread thread handler: it could be modified to support differing threads if necessary.
2. waitOnThread() should occur before the desired thread executes: otherwise you will have multiple threads competing for the handler.
3. This code does not indicate the system is busy if its executing the thread that was put on hold: only if there is a thread on hold.
4. Since waitOnThread() checks for the existence of the thread handler beforehand, it can be used regardless if you expect another thread to be occurring or not.
History
Version 1.0: 2-5-2006