Reputation: 951
I have a library that contains both synchronous and asynchronous implementations of a function, that connects to some hardware and reads some data. Here is the code I'm using:
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
}
}
Why is it that when I use the non blocking asynchronous call, I always receive array filled with NULL objects? This is the first time I'm using this approach, so I'm a little lost here. Thanks for any advice.
Upvotes: 1
Views: 2231
Reputation: 7187
With the asynchronous implementations, the user state is retrieved as it is set during starting the asynchronous operation. Since you pass a string[] with all null values, you get it back.
You are not invoking EndReadID() of the service to get the results.
Try the following: (I am assuming that the service implements the EndReadID method, and it should, if it follows the standard practices)
static void ProcessData(IAsyncResult result)
{
string[] id_read = service.EndReadID(result);
}
Upvotes: 1