using System;
using System.Runtime.Remoting.Contexts;
using System.Threading;
namespace test_synchronization {
[Synchronization(SynchronizationAttribute.REQUIRED, true)] // 整个类都是线程安全
class GuildManager : ContextBoundObject
{
// [MethodImpl(MethodImplOptions.Synchronized)] // 该函数是线程安全
public void Fun(string strPre)
{
if (strPre == "TestFun1")
{
for (int i = 0; i < 30000000; ++i)
{
m_i++;
m_j++;
m_k++;
}
Console.WriteLine(strPre + " outResult, m_i:" + m_i + " m_j:" + m_j + " m_k:" + m_k);
}
else
{
for (int i = 0; i < 30000000; ++i) {
m_i--;
m_j--;
m_k--;
}
Console.WriteLine(strPre + " outResult, m_i:" + m_i + " m_j:" + m_j + " m_k:" + m_k);
}
}
public int m_i = 1;
public int m_j = 1;
public int m_k = 1;
}
class Program {
static void TestFun1(Object state)
{
((GuildManager)state).Fun("TestFun1");
}
static void TestFun2(Object state)
{
((GuildManager)state).Fun("TestFun2");
}
static void Main(string[] args)
{
GuildManager gm = new GuildManager();
ThreadPool.QueueUserWorkItem(TestFun1, gm);
ThreadPool.QueueUserWorkItem(TestFun2, gm);
Console.WriteLine("test synchronization");
Console.ReadLine();
}
}
}