c# - WCF 在关闭 ServiceHost 时等待操作完成

标签 c# .net wcf soap

我创建了一个 WCF SOAP 服务器,其中的操作需要一些时间才能执行:

[ServiceContract]
public interface IMyService
{
    [OperationContract]
    string LongRunningOperation();
}

[ServiceBehavior(
    ConcurrencyMode = ConcurrencyMode.Multiple,
    UseSynchronizationContext = false,
    InstanceContextMode = InstanceContextMode.Single)]
class MyService : IMyService
{
    public string LongRunningOperation()
    {
        Thread.Sleep(20000);
        return "Hey!";
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyService instance = new MyService();
        ServiceHost serviceHost = new ServiceHost(instance);
        BasicHttpBinding binding = new BasicHttpBinding();
        serviceHost.AddServiceEndpoint(typeof(IMyService), binding, "http://localhost:9080/MyService");
        serviceHost.Open();
        Console.WriteLine("Service running");
        Thread.Sleep(10000);
        serviceHost.Close();
        Console.WriteLine("Service closed");
        Thread.Sleep(30000);
        Console.WriteLine("Exiting");
    }
}

ServiceHost 打开,10 秒后我将其关闭。

当调用 serviceHost.Close() 时,所有当前连接的客户端,等待 LongRunningOperation 完成,立即断开连接。

是否有等待以更清洁的方式关闭 ServiceHost?也就是说,我想禁用服务监听器,但还要等待所有当前连接的客户端完成(或指定最大超时)。

最佳答案

我很惊讶调用 ServiceHost.Close 并没有让 LongRunningOperation 完成。

整个架构被设置为允许事物有时间优雅地关闭(例如,关闭和中止转换之间的区别。)。根据 MSDN 文档:

This method causes a CommunicationObject to gracefully transition from any state, other than the Closed state, into the Closed state. The Close method allows any unfinished work to be completed before returning.

ServiceHost 上也有一个 CloseTimeout 正是为了这个。您是否尝试过将 CloseTimeout 设置为大于 20 秒? (根据 Reflector,ServiceHost 的默认 CloseTimeout 为 10 秒...)

关于c# - WCF 在关闭 ServiceHost 时等待操作完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6016568/

相关文章:

c# - 如何从同一个表中的两个不同列读取数据并在字符串生成器中返回?

c# - 我应该将图像作为二进制信息还是作为 FS 上的路径保存到数据库本身?

.net - 无法让 JSONP 与 WCF 数据服务一起使用

c# - WCF 模拟/身份验证

wcf - 如何在不添加服务引用的情况下在 .net core 中使用 wcf?

c# - 签署 ILMerge 的 DLL

c# - C# 中的匿名内部类?

c# - 使用密码在 .net 中创建 zip 文件

c# - 如何从基类中获取对派生类实例的引用

c# - 从 FullyName 字符串到 Type 对象