c# - 由于远程服务未运行,如何中断在连接状态下被阻止的 WCF 代理

标签 c# .net wcf

我已经进行了大量搜索,但未能找到解决方案或答案。我有一个我写的测试应用程序来显示“问题”。 (我对这只是 WCF 的工作方式的想法持开放态度,对此我无能为力。)

我的测试应用程序是一个简单的 WCF 服务和客户端,带有 Visual Studio 生成的代理。我将代理指向已启动但未运行该服务的远程计算机。那一点很重要。如果远程机器根本没有运行,WCF 调用会立即失败。

客户端应用程序创建客户端代理类的一个实例,启动一个新任务,然后尝试调用服务接口(interface),这将被阻止,因为另一端的服务不存在。后台任务休眠 5 秒,然后关闭代理。我原以为另一个线程在关闭代理时会立即出错,但事实并非如此。在发出初始调用约 20 秒后,它就会出现故障。

这是我的客户端代码:

using System;
using System.ServiceModel;
using System.Threading;
using System.Threading.Tasks;
using TestConsoleClient.MyTestServiceReference;

namespace TestConsoleClient
{
class Program
{
    static void Main(string[] args)
    {
        MyTestServiceClient client = new MyTestServiceClient();

        // Start new thread and wait a little bit before trying to close connection.
        Task.Factory.StartNew(() =>
        {
            LogMessage("Sleeping for 5 seconds ...");
            Thread.Sleep(5000);
            if (client == null)
            {
                LogMessage("Woke up!  Proxy was closed before waking up.");
                return;
            }

            LogMessage("Woke up!  Attempting to abort connection.");
            LogMessage(string.Format("Channel state before Close: {0}", 
                ((ICommunicationObject)client).State));

            client.Close();
            ((IDisposable)client).Dispose();
            client.Abort();

            // Channel state is Closed, as expected, but blocked thread does not wake up?
            LogMessage(string.Format("Channel state after Abort: {0}",
                ((ICommunicationObject)client).State));

            client = null;
        });

        // Start connecting.
        LogMessage("Starting connection ...");

        try
        {
            LogMessage("Calling MyTestService.DoWork()");
            client.DoWork();  // Timeout is 60 seconds.  State is "Connecting"
        }
        catch (Exception ex)
        {
            LogMessage(string.Format("Exception caught: {0}", ex.Message));
            if (client != null)
            {
                client.Abort();
                ((IDisposable) client).Dispose();
                client = null;
            }
        }
        finally
        {
            if (client != null)
            {
                client.Close();
                client = null;
            }
        }

        LogMessage("Press Enter to exit ...");

        Console.ReadLine();
    }

    private static void LogMessage(string msg)
    {
        Console.WriteLine("{0}: [{1}] {2}",
                          DateTime.Now.ToString("hh:mm:ss tt"),   Thread.CurrentThread.ManagedThreadId, msg);
    }
}
}

这是我程序的输出:

01:48:31 PM: [9] Starting connection ...
01:48:31 PM: [9] Calling MyTestService.DoWork()
01:48:31 PM: [10] Sleeping for 5 seconds ...
01:48:36 PM: [10] Woke up!  Attempting to abort connection.
01:48:36 PM: [10] Channel state before Close: Opening
01:48:36 PM: [10] Channel state after Abort: Closed
01:48:54 PM: [9] Exception caught: Could not connect to net.tcp://th-niconevm:80
80/MyTestService. The connection attempt lasted for a time span of 00:00:22.0573
009. TCP error code 10060: A connection attempt failed because the connected par
ty did not properly respond after a period of time, or established connection fa
iled because connected host has failed to respond 10.10.10.10:8080.
01:48:54 PM: [9] Press Enter to exit ...

我想要完成的是让用户中断连接,以便他们可以在必要时进行调整,然后重试。正如您在输出中看到的, channel 随后从“Opening”状态变为“Closed”状态,但服务调用一直处于阻塞状态,直到超时。我当然可以解决它,但似乎应该有办法中断它。

这是客户端 app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
    <bindings>
        <netTcpBinding>
            <binding name="NetTcpBinding_IMyTestService" closeTimeout="00:01:00"
                openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
                transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions"
                hostNameComparisonMode="StrongWildcard" listenBacklog="10"
                maxBufferPoolSize="524288" maxBufferSize="65536" maxConnections="10"
                maxReceivedMessageSize="65536">
                <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                    maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                <reliableSession ordered="true" inactivityTimeout="00:10:00"
                    enabled="false" />
                <security mode="Transport">
                    <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
                    <message clientCredentialType="Windows" />
                </security>
            </binding>
        </netTcpBinding>
    </bindings>
    <client>
        <endpoint address="net.tcp://remotehost:8080/MyTestService" binding="netTcpBinding"
            bindingConfiguration="NetTcpBinding_IMyTestService" contract="MyTestServiceReference.IMyTestService"
            name="NetTcpBinding_IMyTestService">
            <identity>
                <userPrincipalName value="remotehost\ClientUser" />
            </identity>
        </endpoint>
    </client>
</system.serviceModel>
</configuration>

最佳答案

如果您使用异步操作生成代理类,您可能会获得更多里程,然后您的代码会变得更加简单。

// Asynchronously call DoWork
MyTestServiceClient client = new MyTestServiceClient();
IAsyncResult iar = client.BeginDoWork(null, null);

// Sleep, dance, do the shopping, whatever
Thread.Sleep(5000);

bool requestCompletedInFiveSeconds = iar.IsCompleted;

// When you're ready, remember to call EndDoWork to tidy up
client.EndDoWork(iar);
client.Close();

如果这听起来可能有帮助,请阅读异步模式。 This MSKB非常有用,并展示了几种编写异步代码的方法。

您的问题实际上可能是无法取消正在进行的 WCF 操作;您将不得不为此编写自己的取消机制。例如,您将无法判断请求是否确实在进行中(即:DoWork 执行需要中止)或者是否存在某些网络或其他机器延迟。

关于c# - 由于远程服务未运行,如何中断在连接状态下被阻止的 WCF 代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13711076/

相关文章:

c# - 如何使用数据库列的值检查组合框的文本

c# - 具有多个构造函数的记录类型

.net - 找不到框架 'Microsoft.NETCore.App' ,版本 '5' ,而找到 Microsoft.NETCore.App 5.0.0

c# - Task.ContinueWith 不适用于 OnlyOnCanceled

c# - 键盘上的特殊键

c# - 获取 ASP.NET System.Web.UI.WebControls.PlaceHolder 的内容

.net - Jenkins .Net和Docker?

wcf - WCF 中的任何 XmlSerialization 限制(相对于 DataContract)?

c# - 如何将请求 header 从跨域传递到WCF服务?

c# - 工作流基础 4.5 InstanceLockedException