Thread-static local-storage : LocalDataStoreSlot « Thread « C# / CSharp Tutorial






using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
using System.Threading;

public class MainClass
{
    [ThreadStatic]
    private static string threadStaticData = "Empty";

    public static void Main()
    {
        Thread[] threads = new Thread[3];
        for (int i = 0; i < 3; i++)
        {
            threads[i] = new Thread(delegate(object j) {
                threadStaticData = "thread no: " + j;
                Console.WriteLine("[Thread{0}] = {1}", j, threadStaticData);
            });
            threads[i].Start(i);                
        }

        foreach (Thread t in threads)
            t.Join();

        Console.WriteLine("[Master] after loop = {0}", threadStaticData);
    }
}
[Thread0] = thread no: 0
[Thread1] = thread no: 1
[Thread2] = thread no: 2
[Master] after loop = Empty








20.26.LocalDataStoreSlot
20.26.1.Thread-local-storage: Unnamed slots
20.26.2.Thread-local-storage: Named slots
20.26.3.Use LocalDataStoreSlot
20.26.4.Thread-static local-storage
20.26.5.Use thread-local storage