zoukankan      html  css  js  c++  java
  • C# 多线程调用静态方法或者静态实例中的同一个方法-方法内部的变量是线程安全的

     C#  多线程调用静态方法或者静态实例中的同一个方法-方法内部的变量是线程安全的

    using System;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Diagnostics;
    using System.Reflection;

    namespace MulThreadTest
    {
    class MainClass
    {

    public static void Main (string[] args)
    {

    for (int i = 0; i < 2; i++) {
    var th=new Thread(
    new ParameterizedThreadStart((state)=>{
    DoHelper.Instance.SayHello(state.ToString());
    })
    );
    th.Start (i);
    }

    Console.ReadKey ();

    }


    }

    public class DoHelper{

    public static DoHelper Instance=new DoHelper();

    public string SayHello(string id){

    string res = "调用Id:" + id;
    StackTrace trace = new StackTrace(true);
    StackFrame frame = trace.GetFrame(1);//1代表上级,2代表上上级,以此类推
    MethodBase method = frame.GetMethod(); //获得当前方法名称


    Console.WriteLine (res);
    Console.WriteLine ("当前方法的Hash code: "+method.GetHashCode());
    /*if (id=="1") {
    System.Threading.Thread.Sleep (5000);
    }
    */
    System.Threading.Thread.Sleep (1000);


    Console.WriteLine ("当前线程上下文Id:"+Thread.CurrentContext.ContextID);
    Console.WriteLine ("当前线程Id:"+Thread.CurrentThread.ManagedThreadId);
    Console.WriteLine ("当前时间:"+DateTime.Now.ToString());
    Console.WriteLine ("当前Trace hashcode :"+trace.GetHashCode());//Variables declared inside methods (with the possible exception of "captured" variables) are isolated,


    return res;
    }

    }
    }

  • 相关阅读:
    由群里在职的同学给出污染物推断题想到的
    参考文献期刊和会议的缩写
    并行程序开发笔记
    对有关推理方法的理解---支离破碎篇
    改基金的困惑与无奈
    对生物信息学基础的补习
    DPI深度报文检测架构及关键技术实现
    OSGi 和 C++
    CentOS安装glibc-2.14,错误安装libc.so.6丢失急救办法
    误删除libc.so.6的解决方法
  • 原文地址:https://www.cnblogs.com/micro-chen/p/10118925.html
Copyright © 2011-2022 走看看