简体   繁体   中英

IAsyncResult AsyncState property is always null

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM