Passing data to a callback method (via BeginInvoke) in C #

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 that res.AsyncState would return the string passed as the last argument in the BeginInvoke call, but this is null. Does anyone know why?

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

+5
source share
3 answers

ar.AsyncState - , BeginInvoke. , result, , "" . result, .

, result BeginInvoke, . , .

, , result - .

+8

, BeginInvoke. . , .

+1

The problem is that you are passing a value result- which is (before doStuff) null. Updates to resultinternally doStuffdo not affect the async state.

+1
source

All Articles