• C#线程本地化存储


          有时以单个线程为基础存储信息比较方便,所存储的信息只对该线程有用,这叫做线程本地化存储。通常用Thread对象的AllocateNamedDataSlot方法创建存储名,用GetData取出内容,最后用FreeNamedDataSlot释放。

         

    1 /*
    2 Example14_4.cs illustrates the use of thread-local storage
    3 */
    4
    5 using System;
    6 using System.Threading;
    7
    8 class Example14_4
    9 {
    10
    11 // the WriteError method writes error info from the current thread
    12 public static void WriteError()
    13 {
    14 Console.WriteLine("Error number = " + Thread.GetData(Thread.GetNamedDataSlot("ErrNo")));
    15 Console.WriteLine("Error source = " + Thread.GetData(Thread.GetNamedDataSlot("ErrSource")));
    16 }
    17
    18 // the SetError method sets a random error number
    19 public static void SetError()
    20 {
    21 Random r = new Random();
    22 Thread.SetData(Thread.GetNamedDataSlot("ErrNo"), r.Next(100));
    23 Thread.SetData(Thread.GetNamedDataSlot("ErrSource") ,Thread.CurrentThread.Name);
    24 WriteError();
    25 }
    26
    27 public static void Main()
    28 {
    29 // allocate some named data slots
    30 Thread.AllocateNamedDataSlot("ErrNo");
    31 Thread.AllocateNamedDataSlot("ErrSource");
    32
    33 // create and start a second thread
    34 Thread t2 = new Thread(new ThreadStart(SetError));
    35 t2.Name = "t2";
    36 t2.Start();
    37
    38 // create a third thread
    39 Thread t3 = new Thread(new ThreadStart(SetError));
    40 t3.Name = "t3";
    41 t3.Start();
    42
    43 // clean up the data slots
    44 Thread.FreeNamedDataSlot("ErrNo");
    45 Thread.FreeNamedDataSlot("ErrSource");
    46
    47 }
    48
    49 }
  • 相关阅读:
    oracle 17068
    Nginx
    B/S端开发工具DevExtreme Angular控件
    UI组件库Kendo UI for Angular入门指南教程
    DevExpress WinForms v21.1
    WPF应用界面开发入门教程
    界面控件Telerik UI for WinForm初级教程
    十六、内联style.html
    十五、css样式class的多种用法
    十四、系统修饰键
  • 原文地址:https://www.cnblogs.com/djcsch2001/p/2042466.html
Copyright © 2020-2023  润新知