![](/img/trans.png)
[英]How IIS control WCF lifetime service wiith InstanceContextmode set to single?
[英]Call asynchronous method on a WCF service with Single InstanceContextMode
我试图在具有单个instanceContextMode的WCF上异步调用一个方法。
有没有办法在等待异步方法时重用服务实例? 我使用Task方式在我的WCF服务引用上生成异步操作。
我做了一个测试项目,因为我的应用程序遇到了一些问题。 我的TestService公开了两种方法:
由于其他一些原因,我的服务应该在Single instanceContextMode中:
[ServiceContract]
public interface ITestService
{
[OperationContract]
string FastMethod(string name);
[OperationContract]
Task<string> LongMethodAsync(string name);
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class TestService : ITestService
{
public TestService() { }
public string FastMethod(string name)
{
Console.WriteLine($"{DateTime.Now.ToLongTimeString()} - FastMethod call - {name}");
return $"FastMethod - {name}";
}
public async Task<string> LongMethodAsync(string name)
{
for (int i = 5; i > 0; i--)
{
await Task.Delay(1000);
Console.WriteLine($"LongMethod pending {i}");
}
Console.WriteLine($"{DateTime.Now.ToLongTimeString()} - LongMethod call - {name}");
return $"LongMethod - {name}";
}
}
我的主机是一个简单的控制台应用程序,它允许我通过Console.WriteLine()方法查看WS调用:
class Program
{
static void Main(string[] args)
{
using (ServiceHost hostTest = new ServiceHost(typeof(TestService)))
{
Console.WriteLine($"{DateTime.Now.ToLongTimeString()} - Service starting...");
hostTest.Open();
Console.WriteLine($"{DateTime.Now.ToLongTimeString()} - Service started");
Console.ReadKey();
hostTest.Close();
}
}
}
在我的客户端,我只有一个显示结果调用的简单表单:
private async void button1_Click(object sender, EventArgs e)
{
string result;
result = srvClient.FastMethod("test1");
resultTextBox.Text = $"{DateTime.Now.ToLongTimeString()} - {result}";
Task<string> t1 = srvClient.LongMethodAsync("test2");
result = srvClient.FastMethod("test3");
resultTextBox.Text += $"\r\n{DateTime.Now.ToLongTimeString()} - {result}";
System.Threading.Thread.Sleep(1000);
result = srvClient.FastMethod("test4");
resultTextBox.Text += $"\r\n{DateTime.Now.ToLongTimeString()} - {result}";
result = await t1;
resultTextBox.Text += $"\r\n{DateTime.Now.ToLongTimeString()} - {result}";
}
当我这样做时,我可以在我的resultTestBox
和主机控制台中看到“test3”和“test4”仅在“test2”结束后被调用。
如果我在本地进行相同的测试(不是通过WCF服务),行为就像预期的那样,“test3”和“test4”在“test2”等待时被调用。
根据MSDN :
如果InstanceContextMode值设置为Single,则结果是您的服务一次只能处理一条消息,除非您还将ConcurrencyMode值设置为ConcurrencyMode。
(看起来他们忘了告诉ConcurrencyMode是什么)
所以只需在服务上设置正确的ConcurrencyMode
:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
确保您的代码是无状态和线程安全的。 这种组合非常容易出错。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.