views:

76

answers:

1

I'm trying to use async from the asp.net mvc futures, using my own async delegate. Haven't figured out how to make it work. Here's the code:

    public delegate String GetString();
    public String getHello() { return "Hello"; }

    public IAsyncResult BeginHello(AsyncCallback cb, Object state)
    {
        GetString dlgt = getHello; 
        return dlgt.BeginInvoke(cb, state);
    }

    public ActionResult EndHello(IAsyncResult asyncResult)
    {
        return View();
    }

In EndHello, asyncResult.IsCompleted=True, but asyncResult.AsyncState==null. I expected to have AsyncState=="Hello".

What am I missing?

Also, does it even make sense to arrange it this way? Or does this cause it to use the same thread pool anyway? Basically my thought was to put a datareader in my asynchronous function, thinking that I could loop through the reader populating a collection of objects and only return when they're done. Is it better to use BeginExecuteReader and populate the objects on the main thread?

EDIT: To anyone reading this later, this is in fact the wrong way to do it, and won't help you at all. BeginExecuteReader is the way to go.

A: 

You will not get Hello in AsyncState.

Hello will be returned when you do an EndInvoke().

e.g. Here's the code you should be using:

public String EndHello(IAsyncResult asyncResult)    
{        
    GetString getStringDel = (asyncResult as AsyncResult).AsyncDelegate as GetString;
    return getStringDel.EndInvoke(asyncResult);
}

You can refer to:

MSDN link Calling Synchronous Methods Asynchronously

SO answer to What is AsyncCallback?

Rashmi Pandit
Thanks! Now I just need to do some testing with wcat and see if this is actually a good idea :)
DennisP