Posts

Showing posts with the label delegate

An Interesting Delegate Usage

An interesting thing happened while I was surfing the MSDN C# forums. I was completely thrown for a loop when I came across some code posted by a regular contributor. It went something like this... private void ACallBackFunction() { if(this.InvokeRequired) this.Invoke(new ThreadStart(ACallBackFunction)); else this.label1.Text = "Something or other"; } The programming pattern should be very familiar to those using threads, because this is how a child thread updates the GUI (only the thread on which the GUI is created can update the UI). But, what seemed very strange was the use of "new ThreadStart(...)". I thought, what does a ThreadStart() delegate have to do with this operation? The answer is ... nothing. But the application is none the less interesting. Here, the programmer decided to draw from a handy delegate in the C# tool chest just to get that required delegate to call "Invoke()" with. ...

Callbacks And Delegates

It's been a couple of weeks since last writing. Besides being very busy, I've had a touch of "writer's block". Nothing too serious, I should get over it soon. Lately, I've been intrigued by the abundant use of callback functions and delegates in the .NET Framework. If you want to do anything interesting, you gotta know callbacks. I'll try to describe callbacks and delegates in simplistic terms. Maybe it will help you over the hump. Consider the following code... List list = new List (); //Populate list with some MyClass objects for(int i=0; i list.Add(new MyClass(){ ID=i, strValue=i.ToString() }); //Sort the list list.Sort(); foreach(MyClass c in list) Console.WriteLine("{0}",c.strValue); ... public class MyClass { public int ID; public string strValue; public override string ToString() { return strValue; } } This code throws an exception at the line that says S...

A Simple Task Queue

I’ve spent the last 4 posts talking about Regular Expressions and some difficult patterns. But, this is a C# blog, so I really want to be talking about C#. Today, I hope to provide you with a nice little start on a multi-threading "Task Queue" application. A Task Queue will place task requests in a queue that will be serviced Asynchronously and in the order received. Rather than keep you in suspense, here’s the code up front. If you'd like an explanation, I've attempted that below. (Update 10/6/2008: Sorry folks about the bug below. The Enqueue method must set the the Busy field to true when queing the first task in order to avoid the thread race. It's now been fixed.) 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.Threading; namespace TaskQueuePOC { public partial class Form1 : Form { public...