Tag Archives: programming

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.

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.  

Programmer’s Paradise

Joel of Joel on Software recently posted a good article on managing programmers in software companies. I liked this paragraph:

A programmer is most productive with a quiet private office, a great computer, unlimited beverages, an ambient temperature between 68 and 72 degrees (F), no glare on the screen, a chair that’s so comfortable you don’t feel it, an administrator that brings them their mail and orders manuals and books, a system administrator who makes the Internet as available as oxygen, a tester to find the bugs they just can’t see, a graphic designer to make their screens beautiful, a team of marketing people to make the masses want their products, a team of sales people to make sure the masses can get these products, some patient tech support saints who help customers get the product working and help the programmers understand what problems are generating the tech support calls, and about a dozen other support and administrative functions which, in a typical company, add up to about 80% of the payroll. It is not a coincidence that the Roman army had a ratio of four servants for every soldier. This was not decadence. Modern armies probably run 7:1.

 I have found that I am far more productive at home than in a cube. At home I have a private office, free drinks, a good computer (not great), two large screens, a perfect temperature, a good chair, and can listen to music out loud.

Programming is an exercise of the mind. The less you have to worry about your body the better your mind functions.

Macros are evil

I’m innocently developing a device context class for my LFC framework and I want a method called SelectPen. All of a sudden I’m getting very weird linker errors about how SelectPen is not defined.

It turns out that SelectPen is a macro defined in windowsx.h as an alias for SelectObject.

#define SelectPen(hdc, hpen) ((HPEN)SelectObject((hdc), (HGDIOBJ)(HPEN)(hpen))) Very annoying.Very annoying.Very annoying.

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.

Still No Silver Bullet…

Much is being made lately about vulnerabilities in Mac OS X, and various people are either haughtily dengrating the Mac while others are pooh-poohing the results with bad logic.

All of the ridiculous claims of “My OS is [better | more secure | safer] than your OS” is getting old. All these problems really do is serve to show us that, once again, that there really is no silver bullet in software design.