Threading

There are 19 entries for the tag Threading

Asynchronous Fire and Forget With Lambdas

I’ve been having trouble getting to sleep lately, so I thought last night that I would put that to use and hack on Subtext a bit. While doing so, I ran into an old Asynchronous Fire and Forget helper method written way back by Mike Woodring which allows you to easily call a delegate asynchronously. On the face of it, it seems like you could simply call BeginInvoke on the delegate and be done with it, Mike’s code addresses a concern with that approach: Starting with the 1.1 release of the .NET Framework, the SDK...

Thread Safety Via Read Only Collections

UPDATE: Made some corrections to the discussion of ReadOnlyCollection’s interface implementations near the bottom. Thanks to Thomas Freudenberg and Damien Guard for pointing out the discrepancy. In a recent post I warned against needlessly using double check locking for static members such as a Singleton. By using a static initializer, the creation of your Singleton member is thread safe. However the story does not end there. One common scenario I often run into is having what is effectively a Singleton collection. For example, suppose you want to expose a collection of all fifty states. This should never change, so you might...

Look Both Ways Before You Lock

Google Code Search is truly the search engine for the uber geek, and potentially a great source of sublime code and sublime comments.  K. Scott Allen, aka Mr. OdeToCode, posted a few choice samples of prose he found while searching through code (Scott, exactly what were you searching for?). One comment he quotes strikes me as a particularly good point to remember about using locks in multithreaded programming. Locks are analogous to green traffic lights: If you have a green light, that does not prevent the idiot coming the other way from plowing into you sideways; it merely guarantees to you that the...

Threading - Never Lock This Redux

A while ago I wrote that you should never lock a value type and never lock this. I presented a code snippet to illustrate the point but I violated the cardinal rule for code examples: compile and test it in context. Mea Culpa! Today in my comments, someone named Jack rightly pointed out that my example doesn’t demonstrate a deadlock due to locking this. As he points out, if the code were in a Finalizer, then my example would be believable. To my defense, I was just testing to see if you were paying attention. ;) Nice find Jack! My...

Threading Tips: Never Lock a Value Type. Never Lock "This".

UPDATE: As a commenter pointed out, the original code example did not properly demonstrate the problem with locking on the this keyword within a normal method. I have corrected this example and wrote a better example that demonstrates that this problem still exists even in a “normal” method. Take a look at this code: private bool isDisposed = false; //... code... ~MyClass() { lock(isDisposed) { if(!isDisposed) { //Do Stuff... ...

Quiz Answer: Watch out for the Eeeevil Thread.Abort.

Yesterday I posted a little quiz with an example of an HttpHandler implemented as an ASHX file. Brad Wilson obviously knew the answer, but only gave a hint for others to elaborate on. BigJimSlade (no link given) expanded on the answer. BigJim, I have a GMail account for you if you want one. Calling HttpResponse.Redirect(string url) actually calls an overload HttpResponse.Redirect(string url, bool endResponse) with endResponse set to true. If endResponse is set to true, HttpResponse.Redirect will make a call to HttpResponse.End(). That method in turn calls Thread.CurrentThread.Abort(). Oh the depravity! Once again, Thread.Abort rears its ugly head. So as you see,...

QUIZ: What's Wrong With This Code?

This is a simplified version of a sneaky bug I ran into today (I’m fine thank you, but the bug is dead). The only prize I can offer is a GMail account if you want one. Imagine that the method HandleRedirect actually does something interesting and if all the conditions pass, the user is redirected to special.aspx. This is the source code for an HttpHandler implemented as a .ashx file. <%@ WebHandler Language="C#" Class="MyHandler" %> using System; using System.Web; public class MyHandler : IHttpHandler { /// <summary> /// Processs an incoming request. /// </summary> ...

More on Terminating Threads and the depravity of Thread.Abort

In response to Ian’s post on thread.abort, Richard Blewett points out a situation when the thread you are attempting to cancel can’t check the volatile book flag to determine whether it should cancel itself or not. An example he presents is when the thread is waiting on a synchronization primitive. The solution given is to call Thread.Interrupt. This is a handy technique when you have a reference to the thread you wish to cancel, but this is not often the case when dealing with asynchronous method calls such as spawned by calling BeginInvoke. You won’t have a reference to the thread...

How To Stop a Thread in .NET (and Why Thread.Abort is Evil)

Ian Griffiths (one of my favorite tech bloggers) wrote this fine piece on why Thread.Abort is a representation of all that is evil and threatens the American (and British) way of life. The problem with Thread.Abort is that it can interrupt the progress of the target thread at any point. It does so by raising an ’asynchronous’ exception, an exception that could emerge at more or less any point in your program. (This has nothing to do with the .NET async pattern by the way - that’s about doing work without hogging the thread that started the work.) If you’re interested...

Doing Work Without Threads

A while ago I wrote up a post on Asynchronous Sockets. Ian was kind enough to send me an email correcting a few niggles with it and in an email exchange, cleared up a few other misconceptions about how sockets (and other IO operations for that matter) really work. Well now he posts a great article that points out that a program doesn't always use a thread to perform some work. There seems to be a popular notion that in order for a program to perform an operation, it must have a thread with which to do it. This is...

Why The ThreadPool Is Very Often The Way To Go

In a previous post, I talked about Anynchronous sockets and its reliance on the ThreadPool and made an uninformed remark about potentially needing to up the ThreadPool count. Ian posted a comment describing why the ThreadPool is very often the way to go for socket programming, correcting my assumption. But as always, measure measure measure to be sure. Go read it. Thanks! Technorati Tags: Threading

A Niggle or Two About Asynchronous Sockets And Thread Safety

Ian Griffiths finds a niggle about my post on sockets. This may surprise a few friends of mine who regard me as a "human dictionary", but I had to look up the word "niggle". Apparently only the "human" part of the appellation applies. I've apparently fooled them by reading a lot of sci-fi fantasy and choosing to learn and use "impressive" words such as Bacchanalian in everyday conversation ("I wrote this code in a drunken stupor from a bacchanalian display of excessive beer drinking."). It's really all smoke and mirrors. But I digress... His comment is quite insightful and well worth repeating...

Why Block At All? Thoughts on threading and sockets

The path of least resistance when writing threading code as well as socket communications is to use techniques that cause indefinite blocking of some sort. Personally, I prefer never to block indefinitely. For example, it's quite common to see code such as: lock(someObject) { //Do Something here... } Nothing wrong with this inherently, but this piece will try to acquire a lock on someObject indefinitely. Imagine if you mistakenly had code like (yes, it's a bit contrived) using System.Threading; //... other stuff ... object someObject = new Object(); object someOtherObject = new object(); public void LockItUp() { lock(someObject) { ...

TimedLock Success Story!

This seems to be my favorite geek subject, but I have to tell you a success story using Ian Griffith's Timed Lock struct with my enhancement. To recap, when you fail to acquire a lock on an object because another thread already has one, my enhancement allows you to see the stack trace of the blocking thread. Well the other day, I was running a suite of unit tests against a socket server I was building when one of the tests failed with a ThreadTimeoutException. Looking at the stack trace, I found the line of code where another thread was...

Thread Naming and Asynchronous Method Calls

Typically when you spawn a new thread, you want to give it a name to facilitate debugging. For example: using System.Threading; //.. other stuff.... Thread thread = new Thread(new ThreadStart(DoSomething); thread.Name = "DoingSomething"; threat.Start(); The code in the method DoSomething (not shown) will run on a thread named "DoingSomething." Now suppose you're writing a socket server using the asynchronous programming model. You might write something that looks like the following: using System.Net.Sockets; using System.Threading; ManualResetEvent allDone = new ManualResetEvent(false); public static void Main() {     Socket socket = new Socket(...); //you get the idea     while(true)     {         allDone.Reset();         socket.BeginAccept(new AsyncCallback(OnSocketAccept), socket);         allDone.WaitOne();     } } public void OnSocketAccept() {     Thread.CurrentThread.Name = "SocketAccepted";     allDone.Set();     // Some socket operation. } In the example above, we're setting up a...

An Even Better TimedLock

Wow! After posting my update to the TimedLock class entitled TimedLock Yet Again Revisited..., Ian Griffiths posts this gem which outlines a solution to one of the problem's with my approach to keeping a stack trace. The problem is that my code acquires a stack trace every time it acquires a lock just in case another thread fails to acquire a lock. The purpose of this action is so that we can examine the stack trace of the blocking thread to find out why we couldn't acquire a lock. This can be a big performance cost in some situations. Ian received...

TimedLock Yet Again Revisited...

In an earlier post, I updated the TimedLock class (first introduced in this post) to allow the user to examine the stack trace of the thread that is holding the lock to an object when the TimedLock fails to obtain a lock on that object. This assumes that the blocking lock was obtained using the TimedLock. Ian Griffiths pointed out a few flaws in my implementation and I promised I would incorporate his feedback and revise the code. Since that time, Ian revisited the TimedLock based on comments he recevied and changed it to be a struct in both...

TimedLock revisited

In an earlier blog entry, I asked the question if it made sense to add code in a debug version of the TimedLock class (written by Ian Griffiths in this post and commented on by Eric Gunnerson in this post) to store the stack trace when acquiring a lock on an object so that if another thread blocks an attempt to acquire a TimedLock, we can discover the StackTrace of the blocking thread. Well I stopped asking questions and started writing answers. I update the TimedLock class with stack trace tracking and also wrote an NUnit test that demonstrates the...

A lock statement with timeout...

Found this on Eric Gunnerson's (PM for the C# compliler team) blog. It's an interesting approach to get a lock statement with a time out. It would be nice to perhaps add a timeout syntax to the lock statement in C#. Maybe it would look like this: object obj = new object(); int milliseconds = 10000;             try {       lock(obj, milliseconds)       {                   //Do something with obj       } } catch(LockTimeOutException exception) {       //Handle exception } One thought I had, and let me know if I'm off base, but it seems we could add debug code to Ian...