[英]IAsyncResult AsyncState property is always null
我有一个库,其中包含函数的同步和异步实现,可连接到某些硬件并读取一些数据。 这是我正在使用的代码:
public class Reader
{
private HardwareService service = new HardwareService();
private string[] id = new string[128];
public string[] ReadData()
{
// Synchronous implementation that works, but blocks the main thread.
return service.ReadID();
}
public void ReadDataAsync()
{
// Asynchronous call, that does not block the main thread, but the data returned in the callback are always null.
AsyncCallback callback = new AsyncCallback(ProcessData);
service.BeginReadID(callback, id);
}
static void ProcessData(IAsyncResult result)
{
string[] id_read = (string[])result.AsyncState; // Always NULL
}
}
为什么在使用非阻塞异步调用时总是收到填充有NULL对象的数组? 这是我第一次使用这种方法,所以我在这里有些迷路。 感谢您的任何建议。
使用异步实现,可以在启动异步操作期间按设置的状态检索用户状态。 由于您传递了一个带有所有空值的string [],因此可以将其取回。
您不是在调用服务的EndReadID()来获取结果。
请尝试以下操作:(我假设服务实现了EndReadID方法,并且如果遵循标准做法,则应该这样做)
static void ProcessData(IAsyncResult result)
{
string[] id_read = service.EndReadID(result);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.