• 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 }
  • 相关阅读:
    [转载]程序员的激情其实是一种痛苦
    利用openSSL 生成RSA公钥和密钥
    表单调试工具推荐
    应该怎么做一个登录功能?
    [转载]常用 SQL Server 规范集锦
    Mock session,cookie,querystring in ASB.NET MVC
    解决VS2013 git客户端遇到的一些问题
    Expression<Func<T>>和Func<T>
    我所理解的领域驱动设计
    月经贴:当落魄的.NET基佬遇上不可一世的JAVA派 developer
  • 原文地址:https://www.cnblogs.com/djcsch2001/p/2042466.html
Copyright © 2020-2023  润新知