Posts

Showing posts with the label Threads

Threading with .NET ThreadPool Part 4

Suppose you've been given the task to write a function that copies the contents of one folder to another. So you set off on your merry way and come up with something like the following. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; namespace ThreadPoolPart4 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { // Get the Folder names, copy contents from one to the other FolderBrowserDialog fb = new FolderBrowserDialog(); fb.ShowDialog(); string src = fb.SelectedPath; fb.ShowDialog(); string dst = fb.SelectedPath; // no error checking on the names, this is an example only if (dst != src)...

Sleep

When I first started programming, I thought "Sleep" to be one of the most useless calls I could make. No, I'm not talking about personal habits, I'm talking about the Sleep() function. using System.Threading; Thread.Sleep(int milliSeconds) We find this little "do nothing" function in C, C++, C#, VB, VB.Net, WScipt, and similar functions in other languages. And, I have since come to understand how useful and confusing "doing nothing" can be. So, let's take a look at it; I'll be focusing on the C# Sleep() function. Sleep() simply suspends the execution of your thread for a specific period of time. It relinquishes the remainder of its time-slice and becomes "unrunnable" for a period of time. If the time period is zero, it relinquish its time-slice only if another thread is ready and waiting to run. If there are no waiting threads, and the time span is zero, the calling thread remains ready to run and therefore returns from Slee...

Threading with .NET ThreadPool Part 3

To wrap up this series of articles, I am going to make the application we've been working on do something a little more interesting. If you will recall in my first article on the subject of ThreadPool , I go over several ways to call the primary thread pool function QueueUserWorkItem and demonstrate how simple it is to multi-thread an application. In my second article, I look at a skeletal application that doesn't really do anything; it just displays messages on the console. However, and more importantly, it demonstrates some of the aspects of synchronization. You must synchronize if you are to do anything of real consequence with threads. So, what sort of interesting things will this application do? My application will paint a pop-art picture. Actually, it will place random pixels on a PictureBox. Okay, its not that useful (or argueably that interesting), but it will demonstrate a means by which threads report progress to the GUI thread. Let's look at the work it...

Threading with .NET ThreadPool Part 2

Let's continue looking at System.Threading.ThreadPool . In the last article , we went over some of the basic features a thread pool should have. We looked specifically at System.Threading.ThreadPool to see how to get your App threading quickly. And, we touched on some aspects missing from Microsoft's thread pool implementation that are needed for an "industrial strength" application. So today, we will examine some of those missing features. Let's start with a skeleton application. This application starts a master work item that is responsible for feeding service work items to the thread pool. The service work items do some work (right now, they display a message with Console.WriteLine(...) and then sleep a random amount of time in the sub-second range). We get a taste of synchronization with the shared random number generator where I surround it with a lock(...){ } statement to make it thread safe. When service work items are done, they exit. "Ex...

Threading with .NET ThreadPool

The System.Threading.ThreadPool is a great little feature for programmers wishing to add instant threading to their applications. You just enqueue callback functions, what could be more simple than that? I agree, so we'll look now at some simple coding experiments with the ThreadPool . By the way, here's the MSDN version of "How to: Use a Thread Pool" which makes for some good pre-requisit reading. And though I risk repeating much of what may be already elsewhere on the web, I hope that I can add something of use in your estimation. So first, let's get a basic understanding of thread pooling. Maybe you've already read my article, Thread Synchronized Queing . If so, you have a good start. A thread pool, like my SynchQueue class, will involve some thread(s) writing to a queue, and some set number of threads reading from the queue. Similarly, if there isn't enough work to do, the reader threads wait or block on the queue. And, if there is too much ...

Timers are a Changin' (Part 3)

In my last couple of articles, we saw the System.Windows.Forms.Timer and the System.Timers.Timer. Today, I shall look at the 3rd form of Timer in the .NET library, the System.Threading.Timer. I refer you again to the that very good article I mentioned a while back, Comparing the Timer Classes in the .NET Framework Class Library by Alex Calvo. Take a moment to read his section on System.Threading.Timer then come back and we will jump right into some code... using System.Threading; public partial class Form1 : Form { public Form1() { InitializeComponent(); timer1 = new System.Threading.Timer(new TimerCallback(timer_elapsed), null, 2000, 1000); } System.Threading.Timer timer1; private void timer_elapsed(object sender) { Console.WriteLine(DateTime.Now.ToString()); TimerEvent(DateTime.Now.ToString(), Thread.CurrentThread.GetHashCode().ToString()); } private delegat...

Timers are a Changin' (Part 2)

Today, I take a look at System.Timers.Timer. I suggested an article in my last discussion of timers. The article was written back in 2004, and it says that both the System.Windows.Forms.Timer and the System.Timers.Timer are found in the IDE Toolbox, one on the Windows Forms tab and the other on the Components tab. Well in my stock installation of Visual Studio 2008, both of those timers are System.Windows.Forms.Timer components. This may be due to some install problem I didn't know I had, or it may be the article is correct for Visual Studio .Net 2003 but not 2008. That's okay because you can just add System.Timers.Timer to your project the old fashioned way. I simply start a new Windows Forms project and name it TimerExample2. After dropping a label on my form, I add the following code to my class file (I include a full listing at the end). System.Timers.Timer timer1; //added public Form1() { InitializeComponent(); // added...

Thread Synchronized Queing

Today's topic gets back to some multi-threading. I find it very useful to have threads pull work from a queue and have one master assignment manager feed the queue. However the standard System.Collections.Generic.Queue is a little inadequate for me because it is not fully thread-safe. I found it a little disheartening that the Queue class members are not overridable either. So we write our own, here are my requirements... The queue must synchronize multiple writer threads writing elements to the queue. The queue must synchronize multiple reader threads reading from the queue. If there is nothing in the queue, a reader thread must wait for something or timeout. Those waiting on the queue can be “interrupted”. Of course, no two readers will ever get the same element off the queue. So let's start coding... I start with a new class called SyncQueue in my own name space and I will make it generic. namespace QueueExample { public class SyncQueue { public void Enqueue(T element)...