【发布时间】:2009-12-02 22:43:34
【问题描述】:
有一段代码:
class WCFConsoleHostApp : IBank
{
private static int _instanceCounter;
public WCFConsoleHostApp ()
{
Interlocked.Increment(ref _instanceCounter);
Console.WriteLine(string.Format("{0:T} Instance nr " + _instanceCounter + " created", DateTime.Now));
}
private static int amount;
static void Main(string[] args)
{
ServiceHost host = new ServiceHost(typeof(WCFConsoleHostApp));
host.Open();
Console.WriteLine("Host is running...");
Console.ReadLine();
}
#region IBank Members
BankOperationResult IBank.Put(int amount)
{
Console.WriteLine(string.Format("{0:00} {1}", Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread) + " Putting...");
WCFConsoleHostApp.amount += amount;
Thread.Sleep(20000);
Console.WriteLine(string.Format("{0:00} {1}", Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread) + " Putting done");
return new BankOperationResult { CurrentAmount = WCFConsoleHostApp.amount, Success = true };
}
BankOperationResult IBank.Withdraw(int amount)
{
Console.WriteLine(string.Format("{0:00} {1}", Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread) + " Withdrawing...");
WCFConsoleHostApp.amount -= amount;
Thread.Sleep(20000);
Console.WriteLine(string.Format("{0:00} {1}", Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread) + " Withdrawing done");
return new BankOperationResult { CurrentAmount = WCFConsoleHostApp.amount, Success = true };
}
#endregion
}
我的测试客户端应用程序在 50 个线程中调用该服务(服务是 PerCall)。我发现非常令人不安的是,当我使用池中的不同线程添加 Thread.Sleep(20000) WCF 每秒创建一个服务实例时。
当我删除 Thread.Sleep(20000) 时,会立即实例化 50 个实例,并且使用大约 2-4 个线程来执行此操作 - 实际上我认为这很正常。
有人能解释一下为什么 Thread.Sleep 在创建实例时会导致这些有趣的延迟吗?
【问题讨论】:
-
我知道这是一个完全不同的问题,但请确保您同步访问静态
amount变量。你现在拥有的不是线程安全的。 -
对,但我很懒...这不是重点 ;)
标签: wcf threadpool