通过下面的代码,我得到:“名称‘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/