Get input argument inside callback method

爷,独闯天下 提交于 2019-12-11 00:30:12

问题


In the code sample below , how to get input argument content inside callback method "MethodDone" ?

I don't want to pass the input parameter again as the third argument of BeginInvoke , 'cause I want to call EndInvoke in callback method .

static class Program
{
    static void Main()
    {
        Action<string> del = new Action<string>(SomeMethod);
        del.BeginInvoke("input parameter", MethodDone, del);
    }

    static void MethodDone(IAsyncResult ar)
    {
        //how to get input parameter here ?

        Action<string> del = (Action<string>)ar.AsyncState;
        del.EndInvoke(ar);
    }

    static void SomeMethod(string input)
    {
        //do something 
    }
}

回答1:


You can write like this and use anything:

static void Main()
    {
        string myInput = "Test";
        Action<string> del = new Action<string>(SomeMethod);
        del.BeginInvoke(
            "input parameter",
            (IAsyncResult ar) =>
                {
                    Console.WriteLine("More Input parameters..." + myInput);
                    del.EndInvoke(ar);
                },
            del);
    }



回答2:


From MSDN:

public delegate void MyDelegate(Label myControl, string myArg2);

private void Button_Click(object sender, EventArgs e)
{
   object[] myArray = new object[2];

   myArray[0] = new Label();
   myArray[1] = "Enter a Value";
   myTextBox.BeginInvoke(new MyDelegate(DelegateMethod), myArray);
}

public void DelegateMethod(Label myControl, string myCaption)
{
   myControl.Location = new Point(16,16);
   myControl.Size = new Size(80, 25);
   myControl.Text = myCaption;
    this.Controls.Add(myControl);
}

Here is the link to the article for further reading: http://msdn.microsoft.com/en-us/library/a06c0dc2(v=vs.110).aspx



来源:https://stackoverflow.com/questions/24244205/get-input-argument-inside-callback-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!