Ejemplo n.º 1
0
 /// <summary> 构造一个计数器,根据参数multiThreadMode确定是否使用多线程模式
 /// <para>多线程模式:在相同线程中,只有第一次执行Add方法时增加引用数,也只有此token被Remove或Dispose才会减少引用数</para>
 /// </summary>
 /// <param name="multiThreadMode"></param>
 public Counter(bool multiThreadMode)
 {
     if (multiThreadMode)
     {
         _dataSlot = Thread.AllocateDataSlot();
     }
 }
Ejemplo n.º 2
0
 public EventProvider(Guid providerGuid)
 {
     this.m_providerId = providerGuid;
     s_returnCodeSlot  = Thread.AllocateDataSlot();
     Thread.SetData(s_returnCodeSlot, 0);
     this.EtwRegister();
 }
Ejemplo n.º 3
0
        static void Main()
        {
            try
            {
                var obj  = new BizObject();
                var pool = new Pool <BizObject>(int.MaxValue, p => new PoolEntry <BizObject>(obj));

                var stopwatch = new Stopwatch();
                var slot      = Thread.AllocateDataSlot();
                Thread.SetData(slot, new object[] { obj });
                BizObject v = obj;
                stopwatch.Start();
                for (var i = 0; i < 1000000; i++)
                {
                    var entry = pool.Acquire();
                    v = entry.Value;
                    pool.Release(entry);
                    //var arr = (object[]) Thread.GetData(slot);
                    //var arr = new object[] {obj};
                    //v = (BizObject)arr[0];
                }
                stopwatch.Stop();

                Console.WriteLine(stopwatch.ElapsedMilliseconds);
                Console.WriteLine(v.IntValue);

                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Ejemplo n.º 4
0
        static TxDataContextDriver()
        {
            AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolve;
            _threadStorageSlot = Thread.AllocateDataSlot();

            CopySampleTraces();
        }
        static void MethodC()
        {
            // 设置主线程名称
            Thread.CurrentThread.Name = "Main Thread";

            // 为所有线程分配未命名的“数据槽位”
            var slot = Thread.AllocateDataSlot();

            // 为所有线程分配命名(username)的“数据槽位”
            //var slot = Thread.AllocateNamedDataSlot("username");
            Thread.SetData(slot, "Hello World A !");

            // 启动工作线程
            var wordThread = new Thread(() =>
            {
                // 在工作线程设置指定槽位的数据
                Thread.SetData(slot, "Hello World B !");
                // 在工作线程获取指定槽位的数据
                Console.WriteLine(Thread.CurrentThread.Name + " - Slot Data - : " + Thread.GetData(slot));
            });

            wordThread.Name = "Work Thread A";
            wordThread.Start();

            // 打印主线程的名称和槽位数据
            Console.WriteLine(Thread.CurrentThread.Name + " - Slot Data - : " + Thread.GetData(slot));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 根据Request对象初始化所需环境信息
        /// </summary>
        /// <param name="request"></param>
        public static void InitHttpEnv(HttpRequest request)
        {
            HttpEnvInfo hei = new HttpEnvInfo(request);

            _HttpEnvSlot = Thread.AllocateDataSlot();
            Thread.SetData(_HttpEnvSlot, hei as IHttpEnvInterface);
        }
Ejemplo n.º 7
0
    public static int Main()
    {
        Console.WriteLine("Hello, World!");
        slot = Thread.AllocateDataSlot();
        LocalDataStoreSlot namedslot = Thread.AllocateNamedDataSlot("data-slot");

        Test   test = new Test();
        Thread thr  = new Thread(new ThreadStart(test.Thread_func));

        thr.Start();
        Thread.Sleep(1000);
        Thread main = Thread.CurrentThread;

        main.Name = "wibble";
        Thread othermain = Thread.CurrentThread;

        Console.WriteLine("Other name " + othermain.Name);
        Thread.Sleep(0);

        Console.WriteLine("In the main line!");

        Console.WriteLine("Trying to enter lock");
        if (Monitor.TryEnter(thr, 100) == true)
        {
            Console.WriteLine("Returned lock");
            Monitor.Exit(thr);
        }
        else
        {
            Console.WriteLine("Didn't get lock");
        }

        Thread.SetData(slot, main);
        Thread storedthr = (Thread)Thread.GetData(slot);

        Console.WriteLine("Stored subthread is " + storedthr.Name);

        Thread.SetData(namedslot, main);
        storedthr = (Thread)Thread.GetData(namedslot);
        Console.WriteLine("Stored subthread is " + storedthr.Name);

        if (thr.Join(5000))
        {
            Console.WriteLine("Joined thread");
        }
        else
        {
            Console.WriteLine("Didn't join thread");
        }

        lock (thr) {
            Monitor.Pulse(thr);
            Console.WriteLine("Signalled thread");
        }

        thr.Join();

        return(0);
    }
Ejemplo n.º 8
0
        /// <summary>
        ///     Allocates the data slot for storing thread-local information.
        /// </summary>
        /// <returns>Allocated slot key.</returns>
        public static object AllocateDataSlot()
        {
#if TLS_WORKAROUND
            return(Interlocked.Increment(ref nextSlotNumber));
#else
            return(Thread.AllocateDataSlot());
#endif
        }
Ejemplo n.º 9
0
        static LogSet()
        {
            _contextSlot = Thread.AllocateDataSlot();

            // mbr - 27-06-2007 - log folder cleanup
            _cleanupCount = new Lookup();
            _cleanupCount.CreateItemValue += new CreateLookupItemEventHandler(_cleanupCount_CreateItemValue);
        }
Ejemplo n.º 10
0
 public NoTrackingThreadLocal(Func <T> valueFactory)
 {
     if (valueFactory == null)
     {
         throw new ArgumentNullException("valueFactory");
     }
     _valueFactory = valueFactory;
     _slot         = Thread.AllocateDataSlot();
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Allocates the data slot for storing thread-local information.
        /// </summary>
        /// <returns>Allocated slot key.</returns>
        public static object AllocateDataSlot()
        {
#if TLS_WORKAROUND
            return(Interlocked.Increment(ref nextSlotNumber));
#elif NETSTANDARD || NET4_6
            return(new System.Threading.ThreadLocal <object>());
#else
            return(Thread.AllocateDataSlot());
#endif
        }
Ejemplo n.º 12
0
        public static void UseUnnamedSlot()
        {
            LocalDataStoreSlot slot = Thread.AllocateDataSlot();

            Thread.SetData(slot, new SomeData());

            object data = Thread.GetData(slot);

            Console.WriteLine(data);
        }
Ejemplo n.º 13
0
        public void Execute()
        {
            ////////////////////////////////////////////////////////////
            //
            // 無名データスロット.
            //    データスロットはどれかのスレッドで最初に作成したら
            //    全てのスレッドに対してスロットが割り当てられる。
            //
            var slot = Thread.AllocateDataSlot();

            var threads = new List <Thread>();

            for (var i = 0; i < 10; i++)
            {
                var thread = new Thread(DoAnonymousDataSlotProcess);
                thread.Name         = $"Thread-{i}";
                thread.IsBackground = true;

                threads.Add(thread);

                thread.Start(slot);
            }

            threads.ForEach(thread => { thread.Join(); });

            Output.WriteLine(string.Empty);

            ////////////////////////////////////////////////////////////
            //
            // 名前付きデータスロット.
            //    名前がつけられる事以外は、無名のスロットと同じです。
            //    名前付きデータスロットは、最初にその名前が呼ばれた
            //    際に作成されます。
            //    FreeNamedDataSlotメソッドを呼ぶと現在のスロット設定
            //    が解放されます。
            //
            threads.Clear();
            for (var i = 0; i < 10; i++)
            {
                var thread = new Thread(DoNamedDataSlotProcess);
                thread.Name         = $"Thread-{i}";
                thread.IsBackground = true;

                threads.Add(thread);

                thread.Start(slot);
            }

            threads.ForEach(thread => { thread.Join(); });

            //
            // 利用したデータスロットを解放.
            //
            Thread.FreeNamedDataSlot("SampleSlot");
        }
Ejemplo n.º 14
0
        public static void OutTask()
        {
            Console.WriteLine(
                "---- class Thread ----\n" +
                "1.Перебор методов и свойств класса. Thread\n" +
                "2.Для создания потока без параметров 'void Name(){}' используется 'new ThreadStart(имя метода)'\n" +
                "Для создания потоков с передачей параметра 'void Name(object name){}' используется 'new ParameterizedThreadStart(имя метода)'\n" +
                "3.Синхронизация потоков:\n" +
                "Синхронизация с использованием lock(object) {}\n" +
                "_______________________________Мониторы\n" +
                "_______________________________Класс AutoResetEvent\n" +
                ""
                );

            Thread thread = Thread.CurrentThread;

            // свойства
            Console.WriteLine($"Имя потока: {thread.Name}");
            Console.WriteLine($"Запущен ли поток: {thread.IsAlive}");
            Console.WriteLine($"Приоритет потока: {thread.Priority}");
            Console.WriteLine($"Статус потока: {thread.ThreadState}");
            Console.WriteLine($"Является ли поток фоновым: {thread.IsBackground}");
            Console.WriteLine($"Текущий запущенный поток: {thread.CurrentCulture}");
            Console.WriteLine($"Задает текущее состояние: {thread.CurrentUICulture}");
            Console.WriteLine($"Принадлежит ли поток управляемому потоку: {thread.IsThreadPoolThread}");
            Console.WriteLine($"Id управляемого потока: {thread.ManagedThreadId}");
            Console.WriteLine($"Домен приложения: {Thread.GetDomain().FriendlyName}");

            // методы
            //thread.Start(); // запускает новый поток
            //thread.Join(); // Блокирует вызывающий поток до тех пор, пока поток, представленный этим экземпляром, не завершится, или не будет продолжен
            //const ApartmentState State = new ApartmentState();
            //thread.SetApartmentState(State); // Задает модель "apartment" для потока до его запуска.
            //thread.TrySetApartmentState(State);
            //thread.Resume(); // продолжать вызывающий поток
            //thread.Abort(); //  уведомляет среду CLR о том, что надо прекратить поток, однако прекращение работы потока происходит не сразу, а только тогда, когда это становится возможно.
            //thread.Suspend(); // или приостанавливает поток, или ничего делает если он уже запущен
            //thread.Interrupt(); // Прерывает поток, который находится в Системе на некоторое время

            Thread.GetDomain();             // возвращает ссылку на домен приложения
            Thread.GetDomainID();           // возвращает id домена приложения, в котором выполняется текущий поток
            Thread.GetCurrentProcessorId(); //
            const int COUNT = 1000;         //

            Thread.Sleep(COUNT);            // останавливает поток на определенное количество миллисекунд
            Thread.SpinWait(COUNT);         //
            Thread.AllocateDataSlot();      //
            Thread.BeginCriticalRegion();   //
            Thread.EndCriticalRegion();     //
            Thread.BeginThreadAffinity();   //
            Thread.EndThreadAffinity();     //
            Thread.MemoryBarrier();         //

            var      arr  = new byte[] { 1, 2, 3, 4, 5 };
            ref byte pArr = ref arr[0];
Ejemplo n.º 15
0
        internal ProjectService()
        {
            extensionChainSlot = Thread.AllocateDataSlot();
            AddinManager.AddExtensionNodeHandler(FileFormatsExtensionPath, OnFormatExtensionChanged);
            AddinManager.AddExtensionNodeHandler(SerializableClassesExtensionPath, OnSerializableExtensionChanged);
            AddinManager.AddExtensionNodeHandler(ExtendedPropertiesExtensionPath, OnPropertiesExtensionChanged);
            AddinManager.AddExtensionNodeHandler(ProjectBindingsExtensionPath, OnProjectsExtensionChanged);
            AddinManager.ExtensionChanged += OnExtensionChanged;

            defaultFormat = formatManager.GetFileFormat("MSBuild10");
        }
Ejemplo n.º 16
0
 /// <summary>Initializes the thread-local data slot</summary>
 private void initializeThreadLocalData()
 {
     if (this.threadLocalDataSlot == null)
     {
         lock (this) {
             if (this.threadLocalDataSlot == null)
             {
                 this.threadLocalDataSlot = Thread.AllocateDataSlot();
             }
         }
     }
 }
Ejemplo n.º 17
0
 private static void SetCallingArguments(NSJSFunctionCallbackInfo arguemnts)
 {
     lock (ldssThreadTable)
     {
         Thread             key = Thread.CurrentThread;
         LocalDataStoreSlot slot;
         if (!ldssThreadTable.TryGetValue(key, out slot))
         {
             slot = Thread.AllocateDataSlot();
             ldssThreadTable.Add(key, slot);
         }
         ldssThreadTable[key] = slot;
         Thread.SetData(slot, arguemnts);
     }
 }
Ejemplo n.º 18
0
        /// <summary>
        /// Provides improved connection flow by providing thread isolated connections for the
        /// lifetime of the disposable.
        /// </summary>
        /// <returns></returns>
        public override IDisposable IsolatedConnections()
        {
            var connection = CreateConnection();

            _isolatedDataStoreSlot = Thread.AllocateDataSlot();
            Thread.SetData(_isolatedDataStoreSlot, connection);

            return(new TrackedDisposable(() =>
            {
                connection.Close();
                connection.Dispose();

                _isolatedDataStoreSlot = null;
            }));
        }
Ejemplo n.º 19
0
        /// <summary>
        /// 为所有线程分配存储的数据槽
        /// </summary>
        public void Fun1()
        {
            var solt = Thread.AllocateDataSlot();

            Thread.SetData(solt, "cheng");

            Thread t = new Thread(() => {
                //工作线程
                var name2 = Thread.GetData(solt);
            });

            t.Start();

            //主线程
            var name = Thread.GetData(solt);
        }
Ejemplo n.º 20
0
        // All threads share a LocalDataStoreSlot object that identifies a thread-local
        // data "slot" that each thread can use. This object must be created in a thread-
        // safe way the first time it becomes necessary. See Thread.AllocateDataSlot().
        internal static LocalDataStoreSlot SafeSlotFetchOrInitialize(ref LocalDataStoreSlot slot,
                                                                     object slotLock)
        {
            // This initialization sequence is meant to be thread-safe
            if (slot == null)
            {
                lock (slotLock) {
                    if (slot == null)
                    {
                        slot = Thread.AllocateDataSlot();
                    }
                }
            }

            return(slot);
        }
 static ThreadTrace()
 {
     logFileName = Environment.GetEnvironmentVariable("ThreadTrace");
     if (logFileName == null)
     {
         logFileName = "";
     }
     isEnabled = logFileName.Length > 0;
     if (isEnabled)
     {
         slot = Thread.AllocateDataSlot();
         logs = new List <ThreadLog>();
         NativeMethods.QueryPerformanceFrequency(out frequency);
         Console.WriteLine("ThreadTrace: enabled");
         new Thread(ThreadProc).Start();
     }
 }
Ejemplo n.º 22
0
        private static BaseLoggingObject LoggingInitialize()
        {
#if MONO_FEATURE_WEB_STACK
#if DEBUG
            if (GetSwitchValue("SystemNetLogging", "System.Net logging module", false) &&
                GetSwitchValue("SystemNetLog_ConnectionMonitor", "System.Net connection monitor thread", false))
            {
                InitConnectionMonitor();
            }
#endif // DEBUG
#endif // MONO_FEATURE_WEB_STACK
#if TRAVE
            // by default we'll log to c:\temp\ so that non interactive services (like w3wp.exe) that don't have environment
            // variables can easily be debugged, note that the ACLs of the directory might need to be adjusted
            if (!GetSwitchValue("SystemNetLog_OverrideDefaults", "System.Net log override default settings", false))
            {
                s_ThreadIdSlot     = Thread.AllocateDataSlot();
                s_UseThreadId      = true;
                s_UseTimeSpan      = true;
                s_DumpWebData      = true;
                s_MaxDumpSize      = 256;
                s_UsePerfCounter   = true;
                s_DebugCallNesting = true;
                s_DumpToConsole    = false;
                s_RootDirectory    = "C:\\Temp\\";
                return(new LoggingObject());
            }
            if (GetSwitchValue("SystemNetLogging", "System.Net logging module", false))
            {
                s_ThreadIdSlot     = Thread.AllocateDataSlot();
                s_UseThreadId      = GetSwitchValue("SystemNetLog_UseThreadId", "System.Net log display system thread id", false);
                s_UseTimeSpan      = GetSwitchValue("SystemNetLog_UseTimeSpan", "System.Net log display ticks as TimeSpan", false);
                s_DumpWebData      = GetSwitchValue("SystemNetLog_DumpWebData", "System.Net log display HTTP send/receive data", false);
                s_MaxDumpSize      = GetSwitchValue("SystemNetLog_MaxDumpSize", "System.Net log max size of display data", 256);
                s_UsePerfCounter   = GetSwitchValue("SystemNetLog_UsePerfCounter", "System.Net log use QueryPerformanceCounter() to get ticks ", false);
                s_DebugCallNesting = GetSwitchValue("SystemNetLog_DebugCallNesting", "System.Net used to debug call nesting", false);
                s_DumpToConsole    = GetSwitchValue("SystemNetLog_DumpToConsole", "System.Net log to console", false);
                s_RootDirectory    = GetSwitchValue("SystemNetLog_RootDirectory", "System.Net root directory of log file", string.Empty);
                return(new LoggingObject());
            }
#endif // TRAVE
            return(new BaseLoggingObject());
        }
Ejemplo n.º 23
0
        public void WhenTestingSpeedOfCallContext_ThenComparesWellAgainstThreadData()
        {
            var iterations = 5000;
            var data       = "foo";
            var threadSlot = Thread.AllocateDataSlot();

            Action threadData = () =>
            {
                Thread.SetData(threadSlot, data);
                var state = Thread.GetData(threadSlot);
                Assert.Equal(state, data);
            };

            Action callContext = () =>
            {
                CallContext.LogicalSetData("slot", data);
                var state = CallContext.LogicalGetData("slot");
                Assert.Equal(state, data);
            };

            Action threadStatic = () =>
            {
                threadStaticData = data;
                var state = threadStaticData;
                Assert.Equal(state, data);
            };

            Action threadLocal = () =>
            {
                threadLocalData = new ThreadLocal <string>(() => data);
                var state = threadLocalData.Value;
                Assert.Equal(state, data);
            };

            // It's best if we test this in multi-threaded scenarios too.
            Time("Thread Data", threadData, iterations);
            Time("CallContext", callContext, iterations);
            Time("ThreadStatic", threadStatic, iterations);
            Time("ThreadLocal", threadLocal, iterations);
        }
Ejemplo n.º 24
0
    public static int Main()
    {
        Console.WriteLine("Hello, World!");
        Test   test = new Test();
        Thread thr  = new Thread(new ThreadStart(test.Thread_func));

        thr.Start();

        for (int i = 0; i < 51200; i++)
        {
            slot[i] = Thread.AllocateDataSlot();
            Thread.SetData(slot[i], i);
        }
        Thread.SetData(slot[11111], 69);
        Thread.SetData(slot[26801], 69);

        Thread.Sleep(10000);

        Console.WriteLine("Main thread done");
        Console.WriteLine("slot 11111 contains " + Thread.GetData(slot[11111]));
        Console.WriteLine("slot 16801 contains " + Thread.GetData(slot[16801]));
        Console.WriteLine("slot 26801 contains " + Thread.GetData(slot[26801]));
        Console.WriteLine("slot 76801 contains " + Thread.GetData(slot[76801]));

        // Test appdomain transitions
        AppDomain ad = AppDomain.CreateDomain("MyFriendlyDomain");
        Test      o  = (Test)ad.CreateInstanceFromAndUnwrap("dataslot.exe", "Test");

        slot2 = Thread.AllocateDataSlot();
        Thread.SetData(slot2, "hello");

        o.Foo(AppDomain.CurrentDomain);

        if (Test.slot_value != "hello")
        {
            return(1);
        }

        return(0);
    }
Ejemplo n.º 25
0
        private static BaseLoggingObject LoggingInitialize()
        {
#if DEBUG
            InitConnectionMonitor();
#endif
#if TRAVE
            s_ThreadIdSlot   = Thread.AllocateDataSlot();
            s_UseThreadId    = GetSwitchValue("SystemNetLog_UseThreadId", "System.Net log display system thread id", false);
            s_UseTimeSpan    = GetSwitchValue("SystemNetLog_UseTimeSpan", "System.Net log display ticks as TimeSpan", false);
            s_DumpWebData    = GetSwitchValue("SystemNetLog_DumpWebData", "System.Net log display HTTP send/receive data", false);
            s_MaxDumpSize    = GetSwitchValue("SystemNetLog_MaxDumpSize", "System.Net log max size of display data", 256);
            s_UsePerfCounter = GetSwitchValue("SystemNetLog_UsePerfCounter", "System.Net log use QueryPerformanceCounter() to get ticks ", false);
            s_DumpToConsole  = GetSwitchValue("SystemNetLog_DumpToConsole", "System.Net log to console", false);

            if (GetSwitchValue("SystemNetLogging", "System.Net logging module", false))
            {
                return(new LoggingObject());
            }
#endif
            // otherwise disable
            return(new BaseLoggingObject());
        }
Ejemplo n.º 26
0
    private void Thread_func()
    {
        Console.WriteLine("In a thread!");

        for (int i = 51200; i < 102400; i++)
        {
            slot[i] = Thread.AllocateDataSlot();
            Thread.SetData(slot[i], i);
        }

        Thread.Sleep(5000);

        Thread.SetData(slot[11111], 42);
        Thread.SetData(slot[76801], 42);

        Thread.Sleep(20000);

        Console.WriteLine("Subthread done");
        Console.WriteLine("slot 11111 contains " + Thread.GetData(slot[11111]));
        Console.WriteLine("slot 26801 contains " + Thread.GetData(slot[26801]));
        Console.WriteLine("slot 76801 contains " + Thread.GetData(slot[76801]));
        Console.WriteLine("slot 96801 contains " + Thread.GetData(slot[96801]));
    }
        static void Main(string[] args)
        {
            //分配一个命名的槽位
            var slot = Thread.AllocateNamedDataSlot("username");
            //分配一个不命名的槽位
            var slot2 = Thread.AllocateDataSlot();

            //释放槽位
            Thread.FreeNamedDataSlot("username");
            //主线程 上 设置槽位,, 也就是hello world 只能被主线程读取,其他线程无法读取
            Thread.SetData(slot, "hello world!!!");
            var t = new Thread(() => {
                var obj = Thread.GetData(slot);
                //新的子线程中无法访问主线程中的变量
                Console.WriteLine("当前工作线程:{0}", obj);
            });

            t.Start();
            var obj2 = Thread.GetData(slot);

            Console.WriteLine("主线程:{0}", obj2);
            Console.Read();
        }
Ejemplo n.º 28
0
        private void LoadData()
        {
            Thread.AllocateDataSlot();

            if (Client.NbrClients > 0)
            {
                for (int i = 0; i < Client.NbrClients; i++)
                {
                    try
                    {
                        Client c = Client.Deserialisation(@"clients\" + i + ".xml");
                        dataGridView1.Rows.Add(c.Numeroinscription, c.Nom, c.Prenom, c.Cin);
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }
            }

            if (Personnel.NbrPersonnels > 0)
            {
                for (int i = 0; i < Personnel.NbrPersonnels; i++)
                {
                    try
                    {
                        Personnel p = Personnel.Deserialisation(@"personnels\" + i + ".txt");
                        dataGridView2.Rows.Add(p.Matricule, p.Nom, p.Prenom, p.Discipline);
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }
            }
        }
Ejemplo n.º 29
0
 static Slot()
 {
     randomGenerator = new Random();
     localSlot       = Thread.AllocateDataSlot();
 }
Ejemplo n.º 30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SystemThreadLocal&lt;T&gt;"/> class.
 /// </summary>
 /// <param name="factory">The factory used to create values when not found.</param>
 public SystemThreadLocal(FactoryDelegate <T> factory)
 {
     m_dataStoreSlot = Thread.AllocateDataSlot();
     m_dataFactory   = factory;
 }