views:

780

answers:

2

I'm working on a project where we mix .NET code and native C++ code via a C++/CLI layer. In this solution I want to use Thread Local Storage via the __declspec(thread) declaration:

__declspec(thread) int lastId = 0;

However, at the first access of the variable, I get a NullReferenceException. To be more precise, the declaration is done within a ref class (a .NET class implemented in C++/CLI).

I have already read something about __declspec(thread) does not work with delay loaded DLLs. Am I using delay loaded DLLs automatically if I use .NET?

+4  A: 

It seems that __declspec(thread) isn't supported by CLR.

Take in mind that .net threads aren't necesarily native threads, but can be also fibers, so standard API's for threads don't work on them.

If you have a managed class, then you should use managed threading API's for thread local storage.

There are a lot of articles regarding this difference. This is just to get you started.

As a tip: You could use the ThreadStatic Attribute instead of the TLS in order to improve performance. In case you are working with ASP.NET applications, you need to remember some things about TLS.

Bogdan Maxim
+3  A: 

Unfortunately not supported. Here's a blog entry with a workaround:

http://blogs.msdn.com/jeremykuhne/archive/2006/04/19/578670.aspx

Bruce