【问题标题】:"unreachable code detected" when in a WCF service在 WCF 服务中“检测到无法访问的代码”
【发布时间】:2013-08-15 18:25:50
【问题描述】:

这个问题与THIS QUESTION 直接相关,但我认为由于主题不同,我会针对当前问题提出一个新问题。我有一个 WCF 服务、一个服务和一个 GUI。 GUI 将一个 int 传递给 WCF,WCF 应该将它存放到 List<int> IntList 中;然后在我想访问列表的服务中。问题是,当我尝试添加到 WCF 服务中的列表时,我收到“检测到无法访问的代码”警告,并且当我通过它进行调试时,添加行被完全跳过。我怎样才能让这个列表“可达”?

以下是 WCF 代码、对 WCF 的 GUI 调用以及使用 WCF 中的List<> 的服务:

WCF:

[ServiceContract(Namespace = "http://CalcRAService")]
public interface ICalculator
{
    [OperationContract]
    int Add(int n1, int n2);
    [OperationContract]
    List<int> GetAllNumbers();
}

// Implement the ICalculator service contract in a service class.
public class CalculatorService : ICalculator
{
    public List<int> m_myValues = new List<int>();

    // Implement the ICalculator methods.
    public int Add(int n1,int n2)
    {
        int result = n1 + n2;
        return result;
        m_myValues.Add(result);
    }
    public List<int> GetAllNumbers()
    {
        return m_myValues;
    }
}

图形界面:

private void button1_Click(object sender, EventArgs e)
        {
            using (ChannelFactory<ICalculator> factory = new ChannelFactory<ICalculator>(new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/MyServiceAddress")))
            {
                ICalculator proxy = factory.CreateChannel();                
                int trouble = proxy.Add((int)NUD.Value,(int)NUD.Value);
            }
        }

服务:

protected override void OnStart(string[] args)
{
    if (mHost != null)
    {
        mHost.Close();
    }
    mHost = new ServiceHost(typeof(CalculatorService), new Uri("net.pipe://localhost"));
    mHost.AddServiceEndpoint(typeof(ICalculator), new NetNamedPipeBinding(), "MyServiceAddress");
    mHost.Open();
    using (ChannelFactory<ICalculator> factory = new ChannelFactory<ICalculator>(new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/MyServiceAddress")))
    {
        ICalculator proxy = factory.CreateChannel();
        BigList.AddRange(proxy.GetAllNumbers());
    }
}

【问题讨论】:

    标签: c# wcf service windows-services


    【解决方案1】:

    所以你有:

    int result = n1 + n2;
    return result; // <-- Return statement
    m_myValues.Add(result); // <-- This code can never be reached!
    

    既然m_myValues.Add() 不会以任何方式改变result 的状态,为什么不翻转这些行:

    int result = n1 + n2;
    m_myValues.Add(result);
    return result;
    

    【讨论】:

    • 我太笨了……当然在return语句后无法访问代码!
    猜你喜欢
    • 2011-05-09
    • 2018-09-21
    • 1970-01-01
    • 2015-06-20
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-22
    相关资源
    最近更新 更多