MSDN :  http://msdn.microsoft.com/ko-kr/library/900fyy8e(v=vs.90).aspx


[C#] Invoke , BeginInvoke, MethodInvoker

원문 : http://uzysjung.springnote.com/pages/5362913
참고 : http://www.devpia.com/MAEUL/Contents/Detail.aspx?BoardID=18&MAEULNO=8&no=1723&page=11



0. 델리게이트 쓰는 방법(0) - 쓰레드에서 콘트롤의 값 가져올 때


public static string readControlText(Control varControl)

{

    if (varControl.InvokeRequired)

    {

        string res = "";

        var action = new Action<Control>(c => res = c.Text);

        varControl.Invoke(action, varControl);

        return res;

    }

    else

    {

        string varText = varControl.Text;

        return varText;

    }

}







1. 델리게이트 쓰는 방법(1)


// 1. 안되는 부분 함수로 만들고

private void SetTxtCB(string txt)

{

    this.textBox1.Text += txt;

}

 

// 2. 델리게이트 선언하고(인수는 함수와 같은 형식으로 만듬)

delegate void SetTextCallback(string txt);

 

// 3. 실제 크로스쓰레드 오류 났던 부분에 델리게이트 집어넣기

private void SetTextonTextBox1(string txt)

{

    if (this.textBox1.InvokeRequired) //델리게이트를 써야하나 검사하고

    {

        this.Invoke(new SetTextCallback(SetTxtCB), new object[] { txt });

        //그냥 txt를 넘겨줘도 된다

    }

    else

    {

        this.textBox1.Text += txt;

    }

}


2. 델리게이트 쓰는 방법(2)

// 1. 델리게이트 선언

public delegate void UpdateText(Control ctrl, string text);

 

// 2. 안되는 부분에 바로 델리게이트 집어넣기

public void UpdateTextFunc(Control ctrl, string text)

{

    if (ctrl.InvokeRequired)

    {

        ctrl.Invoke(new UpdateText(UpdateTextFunc), new object[] { ctrl, text });

    }

    else

        ctrl.Text += text;

}



3. 델리게이트 쓰는 방법(3)

//1. 인자가 없는 메소드 호출시 MethodInvoker를 사용하면 좋다

private void SetTextonTextBox1(string txt)

{

    if (this.textBox1.InvokeRequired)

    { 

        this.Invoke(new MethodInvoker(delegate

     {

                this.textBox1.Text += txt;

       // {} 안에 코드를 넣어주면 된다. 적절한 줄바꿈은 코드를 보기쉽게 한다.
     }));

    }

    else

    {

        this.textBox1.Text += txt;

    }

}






 


Posted by motolies
,