Tag Archives: Code

Pausing a Thread Safely

In .Net you have the option of Thread.Suspend() and Thread.Abort(), but under normal circumstances these are horrible options to use because they’re likely to create locking problems (i.e., the thread has a locks on resource that other threads need).

A far better way is to signal to the thread that it should pause and wait for a signal to continue.  Sometimes it can be as simple as setting a boolean value where both threads can see it. Or you could wrap the boolean value in a property and protect it with a lock, but this is probably overkill for most applications.

To pause a thread safely requires you to use a blocking signal mechanism and .Net has ManualResetEvent for just this purpose.

You could then have some C# code like this:

ManualResetEvent pauseEvent = new ManualResetEvent();

//Thread A (Controlling thread)
void OnPause()
{
 pauseEvent.Reset();
}

void OnStart()
{
pauseEvent.Set();
}

//Thread B (the one to pause)
void ThreadFunction()
{
while(doWork == true)
 {
 //do work
 …
 …

 //wait until event is set
 pauseEvent.WaitOne();
 }
}

This way, you can safely pause work and continue it at a later time, safely avoiding the possibility of deadlocks*.

* Actually, it’s still possible to create a resource locking problem–make sure you release any shared resource locks before pausing.

Free Code Here!

I just received this hilarious message: 

Thanks, you *****, for not responding to my Prim’s e-mail, and may you be cursed with the worst of success in Computer Science.

Sincerely,

Michael

Every once in a while I get requests from people asking me for completed code. The purpose of my articles (and this blog) is to aid understanding, not provide wholesale code. My job keeps me plenty busy, I receive a LOT of e-mails every day, and I probably don’t have the fully-functional, runnable code that people are looking for anyway, when they can probably find it on the Internet.

That said, I have received numerous comments, specific questions, disagreements, kudos, and suggestions that I have warmly responded to.

What’s wrong with this code? – 1

What is wrong with the following code? 

struct Foo {
    public int id;
    public string value;
    public static readonly Foo Empty = new Foo(“”);

    public Foo(string val)
    {
         this.value = val;
         this.id = -1;
     }

};

and elsewhere…

Foo m = new Foo(“Something”); 

if (object.ReferenceEquals(m, Foo.Empty))
{
    …//do something
} else
{

}

 

.Net Deprecation

A useful attribute in .Net is Obselete. When you mark a method with this the compiler will flag any line that accesses the method (or property, or whatever) with a warning (error is optional).

I recently used it for a framework that sits between a database and applications–I wanted to faithfully reflect the database design (since it’s too dangerous to change that), but I want to be warned away from using cetain functionality unless necessary.

Example:

[Obsolete(“You shouldn’t be calling this method!”)]
public void MyMethod()
{

}

Main()
{
    this.MyMethod();
}

The compiler will then say:

warning CS0618: [class…].MyMethod’ is obsolete: ‘You shouldn’t be calling this method!’

Benefits of using “as” in C#

The “as” keyword is very useful in managed code because it solves a very common problem.

Suppose you have this:

object o;


string s = (string)o;

but what if o is null? Then you will get a NullReferenceException. Sometimes this is ok, but often if o is null, you want s to be null as well.

Enter ‘as’. as is like a typecast that will return null if needed.

Your code would then be:

string s = o as string;

This is why you can’t use ‘as’ with value types (int, bool, structs, etc.)–they can’t take on the value of null in the first place. With .Net 2.0, however, the rules change…

Detecting database connection

I have a service that’s absolutely critical to business functions that relies on both Exchange and SQL Server. The problem is that the service’s existing code has a number of places where a failure to connect to the database will result in a dummy, “bad” value being returned from the data access layer. The business layer doesn’t know if the bad values came from bad input data or no database connection, and it assumes the former. This leads to data loss for the customer.

I see three possible solutions for this:

  1. Have an exception for when the database is inaccessible. This is complicated because it changes the code flow, which would not be easy. Every place it tries to access the database would have to handle the exception. I would also have to develop a mechanism to reprocess the data later.
  2. Have a known “bad” value that means database couldn’t be accessed. This is tricky (if not impossible) and would significantly decrease the readability of the code.
  3. Detect whether the database is alive or not before attempting any processing. This avoids the problem of reattempting processing at a later time. It allows more of the code to stay as is (thus fewer chances of new bugs).

I went with 3 because it is also conceptually closer to what should happen. If the database is unavailable, the service can’t possibly do any meaningful work so it should just stop until the database comes back up.

The code to detect a database disconnect is very simple:

static bool IsDatabaseAlive()
{
    SqlConnection connection = null;
    try
    {
        
string strConnection = ConfigurationSettings.AppSettings[“ConnectionString”];
        
using(connection = new SqlConnection(strConnection))
         {
             
connection.Open();
             
return (connection.State != ConnectionState.Open);
          }
     }
    
catch
    
{
         
return false;
     }
}

 

I run this code before running through the processing loops. If the database is alive I go ahead and process.  

Simple Customization of a Collection Class

I needed a simple array of strings today, and I needed to be able to return it via a property. I could use a simple array, but that has some significant drawbacks. I could use an ArrayList, but the indexer returns an object, which would force the application to always cast it. I decided to derive a class from ArrayList and change the indexer. Something like this would work:

public class EmailList : System.Collections.ArrayList
{
public void Add(string email) { base.Add(email); }
public new string this[int index] {
    get { return (string)base[index]; }
    set { base[index] = value; }
  }
}

Notice the “new” keyword for the indexer. This tells the compiler to override the indexer provided by the base class. Now, whatever classes use this class can get a string back from the array list without having to cast it every time. There are other things you can do to customize this collection, but it’s a good start.

Creating an Object-Oriented Framework from an existing API

One of my personal goals this year is to go through Petzold’s book on Programming Windows. During that 1500+ page journey I’m creating a framework class library for my personal use while developing Windows applications. This way I can simultaneously learn the intricacies of Win32 while at the same time developing a framework library that is different than MFC or .Net. Why would I want to do that? Well… MFC isn’t exactly lightweight and it has some performance issues. But aside from that, it’s just fun!

When embarking on something ambitious like this, however, you immediately comes across issues you need to solve, such as how to map an essentially flat API like Win32 into an object-oriented hierarchy of reusable classes. Win32 was, after all, designed before object oriented programming became popular.

There are some patterns that you can use to recognize opportunities for classes and inheritance.

1) Some parameters show up a lot, often as the first argument to a function. All of the GDI functions, for example, take a handle to a device context. This pattern is much like the implicit this parameter in OO programming. A device context is a good candidate for being wrapped into a class, with the GDI functions as members. Most window manipulation functions take as an argument a handle in the form of HWND. Window is another candidate for a class. There are other examples, but these two are good starting places for creating the class hierarchy.

2) There are many variables that are often typecast to other types. Think GDI handles such as HPEN, HBRUSH, and HBITMAP. GDI functions such as SelectObject return a generic HGDIOBJECT which is usually cast to the appropriate HPEN or what-have-you. Fundamentally, these are all the same basic data type–just interpreted differently. This situation is a good candidate for inheritance and polymorphism.

You can also look at other framework libraries for ideas, but this idea is not as attractive, because the point is to develop something original through the learning process, and if those frameworks provided exactly what you wanted, why bother creating a new one anyway? On the other hand, much can be learned by examining proven techniques.

Another big issue you need to deal with in developing a framework library is messaging, but I’ll deal with that in a later post.