A new lock statement for C#

by david 2. October 2009 16:57

I'm working on a lot of multithreaded code at the moment.  In the past I have made use of the lock keyword in C#, but I'm not doing that anymore because it is much better to have a timeout.  However, I don't like having lots of sections like this in my code:

 

if (System.Threading.Monitor.TryEnter(objLock, TIMEOUT))

{

    try

    {

        // do stuff here...

    }

    finally

    {

        System.Threading.Monitor.Exit(objLock);

    }

}

 

...which is the equivalent of using the lock statement, but with a timeout specified.  Still, what I'd like to see in my code is something like this:

 

lock (objLock,TIMEOUT)

{

    // do stuff here...

}

 

Which would be more pretty.  And since I like pretty code, I decided to see how close I could get to that.  This is my current solution:

 

public static class Lock

{

    public static T Try<T>(object objLock, int timeout, Func<T> f)

    {

        if (System.Threading.Monitor.TryEnter(objLock, timeout))

        {

            try

            {

                return f.Invoke();

            }

            finally

            {

                System.Threading.Monitor.Exit(objLock);

            }

        }

        return default(T);

    }

 

    public static void Try(object objLock, int timeout, Action f)

    {

        if (System.Threading.Monitor.TryEnter(objLock, timeout))

        {

            try

            {

                f.Invoke();

            }

            finally

            {

                System.Threading.Monitor.Exit(objLock);

            }

        }

    }

}

 

So far, that is as close as I can get, it means that I can do two things:

 

Lock.Try(objLock, TIMEOUT, delegate

{

    // stuff here...

});

 

or, if I need to return a value, then this:

 

return Lock.Try<int>(objLock,TIMEOUT,delegate

{

    // stuff here...

    return 0;

});

 

Because the second example uses generics, then I can return anything I like by specifying the type inside the angled brackets.  Now I feel that my code is a lot more prettier which is a nice way to finish off on a Friday.

Opening WPF Windows on a new thread

by david 22. September 2009 09:01

Recently I needed to open a new WPF window on a new thread. I was helped a great deal by this article, however the window that I needed to open did not have parameterless constructor.  In the end, this is the code that I came up with:

private void NewWindowThread<T,P>(Func<P, T> constructor, P param) where T : Window

{

   Thread thread = new Thread(() =>

   {

      T w = constructor(param);

      w.Show();

      w.Closed += (sender, e) => w.Dispatcher.InvokeShutdown();

      System.Windows.Threading.Dispatcher.Run();

   });

   thread.SetApartmentState(ApartmentState.STA);

   thread.Start();

}

This method, uses generics to specify the Type of the window that you're creating as well as the Type of the parameter passed to its constructor, for example:

string t = "Hello World!";

NewWindowThread<TitleWindow, string>(c => new TitleWindow(c), t);

Would work when TitleWindow was declared like this:

public class TitleWindow : Window

{

    public TitleWindow(string title)

    {

        this.Title = title;

    }

}

Now I can open different types of window on a new thread and pass parameters to them.

About the author

David
I'm a C# developer having worked with .Net since it was in beta.  Before that I mainly worked in C and C++.  I have been developing commercial software for more than 20 years.  I also mess around with microprocesors, but that's just for fun.  I live near Cambridge, England and at the moment I'm contracted to one of the departments at Cambridge University.