I know there are lot of ways to implement a thread safe singleton pattern like (Double Check Locking , static readonly method, lock method) but i just tried below code
static void Main(string[] args)
{
for (int i = 0; i <= 100; i++)
{
Thread t = new Thread(new ParameterizedThreadStart(doSome));
t.Start(null);
}
Console.ReadLine();
}
private static void doSome(object obj)
{
MyReadOnly obj1 = MyReadOnly.getInstance;
Console.WriteLine(obj1.GetHashCode().ToString());
}
class MyReadOnly
{
private static MyReadOnly instance = new MyReadOnly();
int counter = 0;
// static MyReadOnly()
// {
// } treat is as commented code.
public static MyReadOnly getInstance { get { return instance; } }
private MyReadOnly()
{
Console.WriteLine((++counter).ToString());
}
}
when i see the output of this program , i see just single object created (because of same hashcode)
how to prove that this code is not thread safe?
EDIT
removing static constructor which causes some confusion
That code is thread-safe due to the nature of type initializers in .NET. The type initializer is guaranteed to run exactly once, and if two threads try to run it at the same time, one will do so and the other will block.
See my article on singleton implementation for more details.
This is actually thread-safe code because you are (indirectly) using static constructor to create the instance (And CLR guarantees invocation of static constructor is thread-safe manner on/before access to any other type member).
Related
In other words, is this Singleton implementation thread safe:
public class Singleton
{
private static Singleton instance;
private Singleton() { }
static Singleton()
{
instance = new Singleton();
}
public static Singleton Instance
{
get { return instance; }
}
}
Static constructors are guaranteed to be run only once per application domain, before any instances of a class are created or any static members are accessed. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors
The implementation shown is thread safe for the initial construction, that is, no locking or null testing is required for constructing the Singleton object. However, this does not mean that any use of the instance will be synchronised. There are a variety of ways that this can be done; I've shown one below.
public class Singleton
{
private static Singleton instance;
// Added a static mutex for synchronising use of instance.
private static System.Threading.Mutex mutex;
private Singleton() { }
static Singleton()
{
instance = new Singleton();
mutex = new System.Threading.Mutex();
}
public static Singleton Acquire()
{
mutex.WaitOne();
return instance;
}
// Each call to Acquire() requires a call to Release()
public static void Release()
{
mutex.ReleaseMutex();
}
}
While all of these answers are giving the same general answer, there is one caveat.
Remember that all potential derivations of a generic class are compiled as individual types. So use caution when implementing static constructors for generic types.
class MyObject<T>
{
static MyObject()
{
//this code will get executed for each T.
}
}
EDIT:
Here is the demonstration:
static void Main(string[] args)
{
var obj = new Foo<object>();
var obj2 = new Foo<string>();
}
public class Foo<T>
{
static Foo()
{
System.Diagnostics.Debug.WriteLine(String.Format("Hit {0}", typeof(T).ToString()));
}
}
In the console:
Hit System.Object
Hit System.String
Using a static constructor actually is threadsafe. The static constructor is guaranteed to be executed only once.
From the C# language specification:
The static constructor for a class executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:
An instance of the class is created.
Any of the static members of the class are referenced.
So yes, you can trust that your singleton will be correctly instantiated.
Zooba made an excellent point (and 15 seconds before me, too!) that the static constructor will not guarantee thread-safe shared access to the singleton. That will need to be handled in another manner.
Here's the Cliffnotes version from the above MSDN page on c# singleton:
Use the following pattern, always, you can't go wrong:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
}
Beyond the obvious singleton features, it gives you these two things for free (in respect to singleton in c++):
lazy construction (or no construction if it was never called)
synchronization
Static constructors are guaranteed to fire only once per App Domain so your approach should be OK. However, it is functionally no different from the more concise, inline version:
private static readonly Singleton instance = new Singleton();
Thread safety is more of an issue when you are lazily initializing things.
The static constructor will finish running before any thread is allowed to access the class.
private class InitializerTest
{
static private int _x;
static public string Status()
{
return "_x = " + _x;
}
static InitializerTest()
{
System.Diagnostics.Debug.WriteLine("InitializerTest() starting.");
_x = 1;
Thread.Sleep(3000);
_x = 2;
System.Diagnostics.Debug.WriteLine("InitializerTest() finished.");
}
}
private void ClassInitializerInThread()
{
System.Diagnostics.Debug.WriteLine(Thread.CurrentThread.GetHashCode() + ": ClassInitializerInThread() starting.");
string status = InitializerTest.Status();
System.Diagnostics.Debug.WriteLine(Thread.CurrentThread.GetHashCode() + ": ClassInitializerInThread() status = " + status);
}
private void classInitializerButton_Click(object sender, EventArgs e)
{
new Thread(ClassInitializerInThread).Start();
new Thread(ClassInitializerInThread).Start();
new Thread(ClassInitializerInThread).Start();
}
The code above produced the results below.
10: ClassInitializerInThread() starting.
11: ClassInitializerInThread() starting.
12: ClassInitializerInThread() starting.
InitializerTest() starting.
InitializerTest() finished.
11: ClassInitializerInThread() status = _x = 2
The thread 0x2650 has exited with code 0 (0x0).
10: ClassInitializerInThread() status = _x = 2
The thread 0x1f50 has exited with code 0 (0x0).
12: ClassInitializerInThread() status = _x = 2
The thread 0x73c has exited with code 0 (0x0).
Even though the static constructor took a long time to run, the other threads stopped and waited. All threads read the value of _x set at the bottom of the static constructor.
The Common Language Infrastructure specification guarantees that "a type initializer shall run exactly once for any given type, unless explicitly called by user code." (Section 9.5.3.1.) So unless you have some whacky IL on the loose calling Singleton::.cctor directly (unlikely) your static constructor will run exactly once before the Singleton type is used, only one instance of Singleton will be created, and your Instance property is thread-safe.
Note that if Singleton's constructor accesses the Instance property (even indirectly) then the Instance property will be null. The best you can do is detect when this happens and throw an exception, by checking that instance is non-null in the property accessor. After your static constructor completes the Instance property will be non-null.
As Zoomba's answer points out you will need to make Singleton safe to access from multiple threads, or implement a locking mechanism around using the singleton instance.
Although other answers are mostly correct, there is yet another caveat with static constructors.
As per section II.10.5.3.3 Races and deadlocks of the ECMA-335 Common Language
Infrastructure
Type initialization alone shall not create a deadlock unless some code
called from a type initializer (directly or indirectly) explicitly
invokes blocking operations.
The following code results in a deadlock
using System.Threading;
class MyClass
{
static void Main() { /* Won’t run... the static constructor deadlocks */ }
static MyClass()
{
Thread thread = new Thread(arg => { });
thread.Start();
thread.Join();
}
}
Original author is Igor Ostrovsky, see his post here.
Just to be pedantic, but there is no such thing as a static constructor, but rather static type initializers, here's a small demo of cyclic static constructor dependency which illustrates this point.
Static constructor is guaranteed to be thread safe.
Also, check out the discussion on Singleton at DeveloperZen:
http://web.archive.org/web/20160404231134/http://www.developerzen.com/2007/07/15/whats-wrong-with-this-code-1-discussion/
The static constructor is locked. While the type initializer is running, any other thread which attempts to access the class in such a way that would trigger the type initializer will block.
However, the thread which is running the type initializer can access uninitialized static members. So be sure not to call Monitor.Enter() (lock(){}) or ManualResetEventSlim.Wait() from a type initializer if it is run from a UI thread—those are “interruptible” waits which result in the event loop running, executing arbitrary other parts of your program while your type initializer is still unfinished.
It is preferable for you to use managed blocking rather than unmanaged blocking. WaitHandle.WaitOne, WaitHandle.WaitAny, WaitHandle.WaitAll, Monitor.Enter, Monitor.TryEnter, Thread.Join, GC.WaitForPendingFinalizers, and so on are all responsive to Thread.Interrupt and to Thread.Abort. Also, if your thread is in a single-threaded apartment, all these managed blocking operations will correctly pump messages in your apartment while your thread is blocked:
I have a C# static class accessed from multiple threads. Two questions:
Are my private static fields thread safe when the field is initialized on declaration?
Should I lock when creating private static fields from within static constructor?
Usage of static class from different threads:
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 100; i++)
{
Task.Run(() =>
{
string name = MyStaticClass.GetValue(9555);
//...
});
}
}
}
Option 1 of static class:
public static class MyStaticClass
{
private static MyClass _myClass = new MyClass();
public static string GetValue(int key)
{
return _myClass.GetValue(key);
}
}
Option 2 of static class:
public static class MyStaticClass
{
private static MyClass _myClass;
private static object _lockObj = new object();
static MyStaticClass()
{
InitMyClass();
}
private static void InitMyClass()
{
if (_myClass == null)
{
lock(_lockObj)
{
if (_myClass == null)
{
_myClass = new MyClass();
}
}
}
}
public static string GetValue(int key)
{
return _myClass.GetValue(key);
}
}
Instance class created from the static class:
public class MyClass
{
private Dictionary<int, Guid> _valuesDict = new Dictionary<int, Guid>();
public MyClass()
{
for (int i = 0; i < 10000; i++)
{
_valuesDict.Add(i, Guid.NewGuid());
}
}
public string GetValue(int key)
{
if (_valuesDict.TryGetValue(key, out Guid value))
{
return value.ToString();
}
return string.Empty;
}
}
Should I lock when initializing private static fields from within static constructor?
Let's not bury the lede here:
Never lock in a static constructor. Static constructors are already locked by the framework so that they run on one thread exactly once.
This is a special case of a more general bit of good advice: never do anything fancy with threads in a static constructor. The fact that static constructors are effectively locked, and that lock can be contested by any code that accesses your type, means that you can very quickly get into deadlocks that you did not expect and are hard to see. I give an example here: https://ericlippert.com/2013/01/31/the-no-lock-deadlock/
If you want lazy initialization, use the Lazy<T> construct; it was written by experts who know how to make it safe.
Are my private static fields thread safe when the field is initialized on declaration?
Thread safety is the preservation of program invariants when program elements are called from multiple threads. You haven't said what your invariants are, so it is impossible to say if your program is "safe".
If the invariant you are worried about is that the static constructor is observed to run before the first static method is executed, or the first instance is created, of a type, C# guarantees that. Of course, if you write crazy code in your static constructor, then crazy things can happen, so again, try to keep your static constructors very simple.
fields of static class are not thread safe by default and should avoid unless it is just for read purpose.
Here down side is "lock" as well, it will create serialized processing in multi threaded environment.
public static class MyStaticClass
{
private static MyClass _myClass;
private static object _lockObj;
static MyStaticClass()
{
_myClass = new MyClass();
_lockObj = new object();
}
public static string GetValue(int key)
{
return _myClass.GetValue(key);
}
public static void SetValue(int key)
{
lock(_lockObj)
{
_myClass.SetValue(key);
}
}
}
Your second version is preferable. You can lock it down a little bit more by making your field readonly:
public static class MyStaticClass
{
private static readonly MyClass _myClass = new MyClass();
public static string GetValue(int key)
{
return _myClass.GetValue(key);
}
}
Your intent appears to be that _myClass is initially set to an instance of MyClass and never set to another. readonly accomplishes that by specifying that it can only be set once, either in a static constructor or by initializing it as above. Not only can another thread not set it, but any attempt to change it will result in a compiler error.
You could omit readonly and just never set _myClass again, but readonly both communicates and enforces your intent.
Here's where it gets trickier: Your reference to an instance of MyClass is thread safe. You don't have to worry about whether various threads will replace it with a different instance (or set it to null), and it will be instantiated before any threads attempt to interact with it.
What this does not do is make MyClass thread safe. Without knowing what it does or how you interact with it, there's no way for me to say what the needs or concerns are.
If that is a concern, one approach is to use a lock to prevent concurrent access that shouldn't occur, exactly as #Mahi1722 demonstrated. I'm including the code from that answer (not to plagiarize, but if anything happens to that answer then this one will refer to an answer that doesn't exist.)
public static class MyStaticClass
{
private static MyClass _myClass = new MyClass();
private static object _lockObj = new object();
public static string GetValue(int key)
{
return _myClass.GetValue(key);
}
public static void SetValue(int key)
{
lock(_lockObj)
{
_myClass.SetValue(key);
}
}
}
Both methods that interact with _myClass lock using _lockObject which means that any execution of either will block while another thread is executing either.
That's a valid approach. Another is to actually make MyClass thread safe, either by using concurrent collections or implementing such locks within that class. That way you don't have to use lock statements in every class that uses an instance of MyClass. You can just use it knowing that it manages that internally.
Both are correct,
but there is no need to lock inside static constructor.
So, i will choose the first option, it is shorter and clearer
I have a function which does "migration" from an old format to a new format. I need this to occur in the constructor of my object, but not the static constructor because an argument is needed. How can I have a piece of code only execute exactly one time?
For some context:
class Foo
{
public Foo(string bar)
{
ShouldOnlyExecuteOnce(bar);
}
}
and then usage could be (with each line a different thread)
var f = new Foo("bar");
var fb = new Foo("meh");
etc
How can I properly guard the "ShouldOnlyExecuteOnce" method?
Because this is a sort of "migration" type function, I want for the first object created to "win" and get to migrate the old data into this new object. Later objects that get constructed should not attempt to execute this function, even if their arguments are different
You could use double check locking.
class Foo
{
private static bool ShouldOnlyExecuteOnceExecuted = false;
private static readonly object Locker = new object();
public Foo(string bar)
{
SetShouldOnlyExecuteOnce(bar);
}
private void SetShouldOnlyExecuteOnce(string bar)
{
if(!ShouldOnlyExecuteOnceExecuted)
{
lock(Locker)
{
if(!ShouldOnlyExecuteOnceExecuted)
{
ShouldOnlyExecuteOnce(bar);
ShouldOnlyExecuteOnceExecuted = true;
}
}
}
}
}
I would generally recommend against implementing subtle mechanisms such as double-checked locking, especially when you already have them implemented in the BCL. In this case:
public class SafeInitializater
{
private bool _initialized;
private object _dummy;
private object _syncLock;
public void InitializeOnce(Action initializer)
{
LazyInitializer.EnsureInitialized(ref _dummy, ref _initialized, ref _syncLock,
() => {
initializer();
return null;
});
}
}
Usage sample:
var initializer = new SafeInitializater(); //or you could make this static somewhere
var t1 = Task.Run(() =>
{
Console.WriteLine($"Task {Task.CurrentId} entering the race");
initializer.InitializeOnce(() => Console.WriteLine($"Task {Task.CurrentId} won!"));
});
var t2 = Task.Run(() =>
{
Console.WriteLine($"Task {Task.CurrentId} entering the race");
initializer.InitializeOnce(() => Console.WriteLine($"Task {Task.CurrentId} won!"));
});
await Task.WhenAll(t1, t2);
You need a mutex. This is exactly the kind of usecase mutexes are designed for.
http://www.dotnetperls.com/mutex
you should read about monitors, semaphors and the sigelton design-pattern
What is the Mutex and semaphore In c#? where we need to implement?
http://www.c-sharpcorner.com/UploadFile/1d42da/threading-with-semaphore-in-C-Sharp/
I have no idea, but I'd guess/try:
1 - A static class acting as a wrapper and calls your method in the static constructor
2 - Some IoC container?
3 - Singleton?
4 - Lock?
5 - All of above?
I agree with P.Brian that this seems like a singleton pattern. You can see a very good article on it here http://csharpindepth.com/articles/general/singleton.aspx which breaks it down nicely. Generally the best solution is #4;
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
private Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
A Singleton pattern should work.
Parrotting Jon Skeet: http://csharpindepth.com/articles/general/singleton.aspx
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
private Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
Singleton's are constructed one time. Although, the part about passing in a new string value could present an issue. Is this value ignored on all consecutive calls?
I have problem with the initialization of the static member of a static class. As far as I know, it will be initialized one time only, so I lock this variable when I do fooList.Add(...) in concurrency, to ensure this operation is thread safe:
internal static class ObjectA
{
private static object _lockAdd = new object();
public void functionA()
{
lock (_lockAdd)
{...
I encountered some weird situations, so I decided to write the hashcode of _lockAdd by log4net, and to my surprise this is what I observed:
【INFO】【2012-04-20 15:26:44,080】【thread12】
_lockAdd's hashcode (51755728)...
【INFO】【2012-04-20 15:26:58,624】【thread16】
_lockAdd's hashcode (31071611)...
As you see, the two '_lockAdd ' addresses are different, why is it, or is my understanding of static members wrong ? And how should i do to ensure thread safety when the operation is in a static class?
sorry for the fake code's error, this is my actual code:
internal static class UtilExtension
{
private static object _lockAdd = new object(); //initial twice ? why?
public static void DoAdd(this Type entityType)
{
if (!Pools.Has(entityType))
{
lock (_lockAdd)
{
if (!Pools.Has(entityType)) //insure operation below is thread safe
{
// i find something wrong in concurrency,so i log the _lockAdd's hashcode,
// and then i found it's hashcode is different( in my opinion, it means not the same variables )
LogUtil.Info(_lockAdd.GetHashCode().ToString());
//... do fooList.Add(...)
}
}
}
}
}
For an object only used for locking, use readonly:
private static readonly object _lockAdd = new object();
If the object was getting overwritten somehow, you'll most probably get different results from either the compiler or runtime next time you start the application.
Maybe i make it complicated, the truth is that,the static member is thread unsafe always。So when we use a static member(_lockAdd) as a lock target, we should add readonly to insure the _lockAdd is initilize only once.
In other words, is this Singleton implementation thread safe:
public class Singleton
{
private static Singleton instance;
private Singleton() { }
static Singleton()
{
instance = new Singleton();
}
public static Singleton Instance
{
get { return instance; }
}
}
Static constructors are guaranteed to be run only once per application domain, before any instances of a class are created or any static members are accessed. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors
The implementation shown is thread safe for the initial construction, that is, no locking or null testing is required for constructing the Singleton object. However, this does not mean that any use of the instance will be synchronised. There are a variety of ways that this can be done; I've shown one below.
public class Singleton
{
private static Singleton instance;
// Added a static mutex for synchronising use of instance.
private static System.Threading.Mutex mutex;
private Singleton() { }
static Singleton()
{
instance = new Singleton();
mutex = new System.Threading.Mutex();
}
public static Singleton Acquire()
{
mutex.WaitOne();
return instance;
}
// Each call to Acquire() requires a call to Release()
public static void Release()
{
mutex.ReleaseMutex();
}
}
While all of these answers are giving the same general answer, there is one caveat.
Remember that all potential derivations of a generic class are compiled as individual types. So use caution when implementing static constructors for generic types.
class MyObject<T>
{
static MyObject()
{
//this code will get executed for each T.
}
}
EDIT:
Here is the demonstration:
static void Main(string[] args)
{
var obj = new Foo<object>();
var obj2 = new Foo<string>();
}
public class Foo<T>
{
static Foo()
{
System.Diagnostics.Debug.WriteLine(String.Format("Hit {0}", typeof(T).ToString()));
}
}
In the console:
Hit System.Object
Hit System.String
Using a static constructor actually is threadsafe. The static constructor is guaranteed to be executed only once.
From the C# language specification:
The static constructor for a class executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:
An instance of the class is created.
Any of the static members of the class are referenced.
So yes, you can trust that your singleton will be correctly instantiated.
Zooba made an excellent point (and 15 seconds before me, too!) that the static constructor will not guarantee thread-safe shared access to the singleton. That will need to be handled in another manner.
Here's the Cliffnotes version from the above MSDN page on c# singleton:
Use the following pattern, always, you can't go wrong:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
}
Beyond the obvious singleton features, it gives you these two things for free (in respect to singleton in c++):
lazy construction (or no construction if it was never called)
synchronization
Static constructors are guaranteed to fire only once per App Domain so your approach should be OK. However, it is functionally no different from the more concise, inline version:
private static readonly Singleton instance = new Singleton();
Thread safety is more of an issue when you are lazily initializing things.
The static constructor will finish running before any thread is allowed to access the class.
private class InitializerTest
{
static private int _x;
static public string Status()
{
return "_x = " + _x;
}
static InitializerTest()
{
System.Diagnostics.Debug.WriteLine("InitializerTest() starting.");
_x = 1;
Thread.Sleep(3000);
_x = 2;
System.Diagnostics.Debug.WriteLine("InitializerTest() finished.");
}
}
private void ClassInitializerInThread()
{
System.Diagnostics.Debug.WriteLine(Thread.CurrentThread.GetHashCode() + ": ClassInitializerInThread() starting.");
string status = InitializerTest.Status();
System.Diagnostics.Debug.WriteLine(Thread.CurrentThread.GetHashCode() + ": ClassInitializerInThread() status = " + status);
}
private void classInitializerButton_Click(object sender, EventArgs e)
{
new Thread(ClassInitializerInThread).Start();
new Thread(ClassInitializerInThread).Start();
new Thread(ClassInitializerInThread).Start();
}
The code above produced the results below.
10: ClassInitializerInThread() starting.
11: ClassInitializerInThread() starting.
12: ClassInitializerInThread() starting.
InitializerTest() starting.
InitializerTest() finished.
11: ClassInitializerInThread() status = _x = 2
The thread 0x2650 has exited with code 0 (0x0).
10: ClassInitializerInThread() status = _x = 2
The thread 0x1f50 has exited with code 0 (0x0).
12: ClassInitializerInThread() status = _x = 2
The thread 0x73c has exited with code 0 (0x0).
Even though the static constructor took a long time to run, the other threads stopped and waited. All threads read the value of _x set at the bottom of the static constructor.
The Common Language Infrastructure specification guarantees that "a type initializer shall run exactly once for any given type, unless explicitly called by user code." (Section 9.5.3.1.) So unless you have some whacky IL on the loose calling Singleton::.cctor directly (unlikely) your static constructor will run exactly once before the Singleton type is used, only one instance of Singleton will be created, and your Instance property is thread-safe.
Note that if Singleton's constructor accesses the Instance property (even indirectly) then the Instance property will be null. The best you can do is detect when this happens and throw an exception, by checking that instance is non-null in the property accessor. After your static constructor completes the Instance property will be non-null.
As Zoomba's answer points out you will need to make Singleton safe to access from multiple threads, or implement a locking mechanism around using the singleton instance.
Although other answers are mostly correct, there is yet another caveat with static constructors.
As per section II.10.5.3.3 Races and deadlocks of the ECMA-335 Common Language
Infrastructure
Type initialization alone shall not create a deadlock unless some code
called from a type initializer (directly or indirectly) explicitly
invokes blocking operations.
The following code results in a deadlock
using System.Threading;
class MyClass
{
static void Main() { /* Won’t run... the static constructor deadlocks */ }
static MyClass()
{
Thread thread = new Thread(arg => { });
thread.Start();
thread.Join();
}
}
Original author is Igor Ostrovsky, see his post here.
Just to be pedantic, but there is no such thing as a static constructor, but rather static type initializers, here's a small demo of cyclic static constructor dependency which illustrates this point.
Static constructor is guaranteed to be thread safe.
Also, check out the discussion on Singleton at DeveloperZen:
http://web.archive.org/web/20160404231134/http://www.developerzen.com/2007/07/15/whats-wrong-with-this-code-1-discussion/
The static constructor is locked. While the type initializer is running, any other thread which attempts to access the class in such a way that would trigger the type initializer will block.
However, the thread which is running the type initializer can access uninitialized static members. So be sure not to call Monitor.Enter() (lock(){}) or ManualResetEventSlim.Wait() from a type initializer if it is run from a UI thread—those are “interruptible” waits which result in the event loop running, executing arbitrary other parts of your program while your type initializer is still unfinished.
It is preferable for you to use managed blocking rather than unmanaged blocking. WaitHandle.WaitOne, WaitHandle.WaitAny, WaitHandle.WaitAll, Monitor.Enter, Monitor.TryEnter, Thread.Join, GC.WaitForPendingFinalizers, and so on are all responsive to Thread.Interrupt and to Thread.Abort. Also, if your thread is in a single-threaded apartment, all these managed blocking operations will correctly pump messages in your apartment while your thread is blocked: