views:

819

answers:

3

I have the following code:

    delegate int doStuffDel(int instanceNo, int sleepTime, int repeatCount);
    string result;

    private int doStuff(int instanceNo, int sleepTime, int repeatCount)
    {
        for (int i = 0; i < repeatCount; i++)
        {
            Console.Write(instanceNo);
            Thread.Sleep(sleepTime);
        }
        result = instanceNo + " repeated " + repeatCount;
        return instanceNo;
    }

    private void button3_Click(object sender, EventArgs e)
    {
        doStuffDel del = doStuff;
        IAsyncResult ar = del.BeginInvoke(3, 120, 50, finishedCallback, result);
    }

    private void finishedCallback(IAsyncResult ar)
    {
        Console.WriteLine("Done. The result was " + ar.AsyncState.ToString());
    }

I thought the res.AsyncState would return the string, passed as the last argument in the call to BeginInvoke, but it's null. Does anybody know why?

PS, I know I could pass the del as the last argument in BeginInvoke and then call EndInvoke in the callback, to get some result from the doStuff method, -- or I could just get the string val from the class! -- but I am surpised that the AsyncState on the AsyncResult object is null...

Any help much appreciated!

JS

+5  A: 

The value of ar.AsyncState is the value of result when you originally pass it to BeginInvoke. The fact that when you passed it, you used the value of result doesn't mean that it's "bound" to the result variable. It's just the value of the result variable when you pass it to start with.

To see this, either set result to some test value before calling BeginInvoke, or just pass a string literal instead. Either way, you'll get that value in the callback.

On the other hand, your callback and original delegate both have the same target object, so you could use use result within the callback and it would have the value you want - that's another way of maintaining state.

Jon Skeet
+1  A: 

It's passed in when you call BeginInvoke. At that time, result is null. If you set result before the call, you'll see it in the callback.

John Saunders
+1  A: 

The problem is that you pass the value of result - which (before doStuff) is null. Updates to result within doStuff do not affect the async state.

Marc Gravell