c# - 为什么我在本地声明的变量在 finally block 中没有被识别?

标签 c# sockets

通过下面的代码,我得到:“名称‘listener’在当前上下文中不存在”

真的吗?为什么?

static void ReceiveSocketMsgs()
{
    try
    {
        TcpListener listener;
        listener = new TcpListener(IPAddress.Any, MainForm.GOHRFTrackerMainForm.socketPortNum);
        listener.Start();
        using (TcpClient c = listener.AcceptTcpClient())
        {
            using (NetworkStream n = c.GetStream())
            {
                string msg = new BinaryReader(n).ReadString();
                BinaryWriter w = new BinaryWriter(n);
                w.Write(msg + " received");
                w.Flush(); // Must call Flush because we're not disposing the writer. 
            }
        }
    }
    catch (Exception ex)
    {
        //some exception (if you close the app, it will be "threadabort")
    }
    finally
    {
        listener.Stop();
    }
}

最佳答案

这就是 C# 作用域的工作原理。它确实妨碍了 lock 语句和 try/catch 子句。只需将声明移到外面:

static void ReceiveSocketMsgs()
{
    TcpListener listener = null;
    try
    {
        listener = new TcpListener(IPAddress.Any, MainForm.GOHRFTrackerMainForm.socketPortNum);
        ...
    }
    catch (Exception ex)
    {
        //some exception (if you close the app, it will be "threadabort")
    }
    finally
    {
        if (listener != null)
            listener.Stop();
    }
}

要将监听器初始化保持在 try block 内,请将变量初始化为 null 并在调用 Stop 之前检查它。

修复了初始化。很好地发现了 BoltClock。

关于c# - 为什么我在本地声明的变量在 finally block 中没有被识别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8857066/

相关文章:

c# - Xamarin : iOS won't send punctuation in strings to a web endpoint

javascript - 断开或重新加载时Io套接字重置连接

c - 为什么网络服务器在发送响应之前应该清除套接字接收缓冲区?

c - 在同一多播地址上加入源特定多播

c# - “资源”在当前上下文中不存在

c# - 使用 Json.Net 仅序列化选定的属性

c# - 根据特定条件在字符串中搜索子字符串

python - 使用 Twisted (python) 为 UDP 套接字设置超时

java 7套接字监听异常

c# - 如何在 JavaScript 中的复选框 checkin 上启用和禁用 Ajax 评级控制