您的位置:首页 > 编程语言 > C#

what is new - .NET 4.5: review of the ThreadLocal

2013-01-24 00:00 495 查看
ThreadLocal is a managed impl of the windows thread local storage, basically with thread local, only the creator of the thread local variable can see/save/load values of the thread local variables. It is a means of isolation. Let's first examine an example of the
ThreadLocal<T> class

A threadLocal storage will be created when it is first used. it is one time task for each thread. Below is an adapted code with my own comments in.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ThreadLocalStorage
{
// boqwang:
//  in this example, we will going to examing the thread-local storage as it is supported by the CLR runtime.
class Program
{
static void Main(string[] args)
{
ThreadLocal<string> ThreadName = new ThreadLocal<string>(() =>  // initialize the thread local storage with the
{
return "Threadi" + Thread.CurrentThread.ManagedThreadId;
});

Action action = () =>
{
bool repeat = ThreadName.IsValueCreated; // you can check to see if the ThreadLocal variable is created, for threadlocal, only the creator can see it.
Console.WriteLine("ThreadName = {0} {1}", ThreadName.Value, repeat ? "(repeat)" : ""); // repeat here means we are running on the same thread which creates the thread local storage...
};

// Launch eight of them.  On 4 cores or less, you should see some repeat ThreadNames
Parallel.Invoke(action, action, action, action, action, action, action, action);

// Dispose when you are done
ThreadName.Dispose();   // -- remember to deallocate if you are done with it. ..
}
}
}
the output is something as follow.

ThreadName = Threadi4
ThreadName = Threadi4 (repeat)
ThreadName = Threadi4 (repeat)
ThreadName = Threadi3
ThreadName = Threadi3 (repeat)
ThreadName = Threadi3 (repeat)
ThreadName = Threadi3 (repeat)
ThreadName = Threadi4 (repeat)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  .net c#
相关文章推荐