c# - 在执行 BeginRead 时,我是否总是需要将我的 Socket 作为状态参数的一部分传递?

标签 c# sockets asynchronous

它在 MSDN documentation 中声明那:

at the very minimum, your state parameter must contain the connected or default Socket being used for communication. Since you will want to obtain the received data within your callback method, you should create a small class or structure to hold a read buffer, and any other useful information. Pass the structure or class instance to the BeginReceive method through the state parameter.



但是我调用 BeginRecieve 并将实例方法作为我的 AsyncCallback 传递:
class MyClass
{
    private Socket mysocket;

    private void callback(IAsyncResult Result)
    {
        Record record = this.mysocket.EndReadRecord(Result);
        // Do things
        this.mysocket.BeginReadRecord(new AsyncCallback(callback), null);
    }

    // Other methods
}

假设 mysocket只设置一次(在构造函数期间),是否需要将我的套接字作为状态参数的一部分传递,或者使用实例字段 mysocket 是否安全?

最佳答案

如果您只在回调期间触摸它,或者基本上以孤立的方式触摸它,您将是安全的。

这往往是我处理委托(delegate)的方式,在方法范围之外定义一个委托(delegate)变量以在回调期间使用它。

关于c# - 在执行 BeginRead 时,我是否总是需要将我的 Socket 作为状态参数的一部分传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3386405/

相关文章:

c# - WinForm和uwp如何双向通信

c++ - 套接字编程学习

c++ - char 数组到字符串的转换会导致奇怪的字符 - 套接字

c# - ASP.NET MVC 中的异步方法

javascript - Node.js forEach 放入数组

c# - 用户代码未处理 invalidCastException

c# - 是否有工具可以查找使用 OpenXML SDK 创建的 Excel 文档中的错误?

c# - EntityFramework 6 基于代码的数据库优先连接字符串配置

c - 使用 CURL 测试时,我的 C 程序在接受连接时被卡住

c# - 在 cshtml 页面内异步加载