C#靜態方法在多用戶併發訪問時,運行狀況究竟是什麼樣?是排隊等待?仍是併發的?

曾經有個錯誤的認識,一直覺得靜態方法在多用戶併發下會是排隊等待,一個個執行,前些日子與朋友 單程列車 http://www.cnblogs.com/zhaojingjing/  一塊兒作了測試後才發現,原來是併發執行的,絕對不會排隊等待。併發

  寫程序的不能怕丟人有錯就改,積極改正錯誤,一天比一天上一個臺階就好。ide


模擬併發的測試代碼以下,但願對有須要的朋友提供的方便的參考測試

複製代碼
// --------------------------------------------------------------------
// All Rights Reserved , Copyright (C) 2011 , Hairihan TECH, Ltd.
// --------------------------------------------------------------------

namespace DotNet.Example
{
using DotNet.BaseManager;

public class StaticTest
   {
/// <summary>
/// 定義委託
/// </summary>
/// <param name="user"> 用戶 </param>
delegate void MakeStaticDelegate( string user);

/// <summary>
/// 這裏是測試靜態方法
/// </summary>
/// <param name="user"> 用戶 </param>
private static void MakeStaticTest( string user)
       {
for ( int i = 0 ; i < 10 ; i ++ )
           {
// 輸出當前的變量
               System.Console.WriteLine(user + " " + i.ToString());
               System.Threading.Thread.Sleep(
1000 );
           }
       }

/// <summary>
/// 這裏是模擬多用戶同時點擊併發
/// </summary>
public void DoTest()
       {
// 模擬3個用戶的併發操做
           MakeStaticDelegate makeStaticDelegate1 = new MakeStaticDelegate(MakeStaticTest);
           makeStaticDelegate1.BeginInvoke(
" user1 " , null , null );
           MakeStaticDelegate makeStaticDelegate2
= new MakeStaticDelegate(MakeStaticTest);
           makeStaticDelegate2.BeginInvoke(
" user2 " , null , null );
           MakeStaticDelegate makeStaticDelegate3
= new MakeStaticDelegate(MakeStaticTest);
           makeStaticDelegate3.BeginInvoke(
" user3 " , null , null );
           System.Console.ReadLine();
       }
   }
複製代碼

}
spa

相關文章
相關標籤/搜索