2015-11-30 27 views
0

我有一个库,它包含一个函数的同步和异步实现,它连接到某个硬件并读取一些数据。下面是我使用的代码:IAsyncResult AsyncState属性始终为空

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填充对象?这是我第一次使用这种方法,所以我在这里有点迷路。感谢您的任何建议。

回答

1

使用异步实现时,将在启动异步操作期间设置用户状态。由于您使用全部空值传递字符串[],因此您可以将其返回。

您没有调用服务的EndReadID()来获得结果。

尝试以下方法:(我假设服务实现了EndReadID方法,它应该,如果按照标准的做法)

static void ProcessData(IAsyncResult result) 
{ 
    string[] id_read = service.EndReadID(result); 
} 
+0

大,这样的作品,谢谢!我只是不知道为什么我必须将一个对象实例传递给BeginReadID函数,因为我正在通过调用EndReadID来读取对象的新实例。 –

+0

@Tomáš'GunsBlazing'Frček用户状态对于将对象传递给回调方法非常有用。回调方法可以在任何线程中执行,并且可以是静态等,从而与上下文断开连接开始操作。您不必将任何东西放入状态,因为1.您不需要任何东西,但服务实例,2.您的回调函数是您类的实例成员,并且可以访问其中的其他成员(例如:服务实例) –

+0

@Tomáš'GunsBlazing'Frček只是在这些情况下传递null。 –