曾经有个错误的认识,一直以为静态方法在多用户并发下会是排队等待,一个个执行,前些日子与朋友 单程列车 http://www.cnblogs.com/zhaojingjing/ 一起做了测试后才发现,原来是并发执行的,绝对不会排队等待。
写程序的不能怕丢人有错就改,积极改正错误,一天比一天上一个台阶就好。
模拟并发的测试代码如下,希望对有需要的朋友提供的方便的参考
//
--------------------------------------------------------------------
// 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();
}
}
// 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();
}
}
}