http://www.masque.kr/free/383086



 

스레드 - 컨트롤Invoke(동기), BeginInvoke(비동기)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public Form1()
{
    InitializeComponent();
 
    var thread = new Thread(OneThread);
    thread.Name = "OneThread";
    thread.Start();
}
 
private void OneThread()
{
    var i = 0;
    while (true)
    {
        try
        {
            // Thread Safe
            // 동기
            //Invoke(new TextHandler(UpdateButtonText), new object[] { "스레드" + i });
 
            // 비동기
            BeginInvoke((MethodInvoker)(() => { button1.Text = "스레드" + i; button1.Update(); }));
            //BeginInvoke((MethodInvoker)delegate { button1.Text = "스레드" + i; button1.Update(); });
            //BeginInvoke((MethodInvoker)(() => UpdateButtonText("스레드" + i )));
            //BeginInvoke(new TextHandler(UpdateButtonText), "스레드" + i);
            //BeginInvoke(new TextHandler(UpdateButtonText), new object[] { "스레드" + i });
 
            // Cross Thread
            //button1.Text = "테스트";
            //button1.Update();
        }
        catch (Exception e)
        {
            // 크로스 스레드 작업이 잘못되었습니다.
            // button1' 컨트롤이 자신이 만들어진 스레드가 아닌 스레드에서 액세스되었습니다.
        }
 
        i++;
    }
}
 
//public delegate void TextHandler(String text);
//private void UpdateButtonText(String text)
//{
//    button1.Text = text;
//    button1.Update();
//}

참고
 - https://msdn.microsoft.com/ko-kr/library/ms171728%28v=vs.110%29.aspx
  

 - http://stackoverflow.com/questions/253138/anonymous-method-in-invoke-call
버튼과 같은 스레드로 접근을 하여 크로스 스레드를 피할수 있다

성능면에서 동기는 기다리고, 비동기는 끝날때 호출되어 자원을 효율적으로 사용한다.

InvokeRequired는 성능과는 무관하고, 같은 스레드인지 확인용이다.

 


동기 : 보통의 프로그래밍환경, 한 라인씩 실행한다.

비동기 : 스레드를 생성하여, 실행한다. 모두 처리하지 않아도 다음라인으로 넘어간다.

           서버와 통신할때 기다릴 필요없이 다음 라인을 실행할수 있다.

 

UI.BeginInvoke : 비동기로 대리자를 실행한다. 스레드는 UI와 동일, 스레드충돌해결
대리자.BeginInvoke : 비동기로 자신을 실행한다. 스레드풀의 스레드를 사용

BeginInvoke보이지 않으면, "고급 멤버 숨기기"를 체크 해제 한다

 

동기를 해야 할때

하늘에서 운석이 떨어진다. 지구종말 시간이 가까워 졌다.

여자친구와 헤어졌다. 인생 허무하다.

블리자드가 망해서, 배틀넷이 정지되고, 계정이 잠겼다.

MB의 잘못이 모두 드러나고, 사형집행이 결정되었다. 장소는 서울시청앞

 

비동기를 해야 할때

로그인등, 일반적인 프로젝트 상황

로그인은 동기로 해야 할거 같다고 생각했는데, 실제로는 동기가 되면, 대화상자가 응답없음이 되어 버린다.

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public delegate void TextHandler(String text);
private void UpdateButtonText(String text)
{
    if (this.button1.InvokeRequired)
    {
        this.Invoke(new TextHandler(UpdateButtonText), new object[] { text });
    }
    else
    {
        this.button1.Text = text;
        this.button1.Update();
    }
}
// InvokeRequired예제, 동기사용, 비권장

참고 https://msdn.microsoft.com/ko-kr/library/ms171728(v=vs.110).aspx


'Knowledge' 카테고리의 다른 글

[UWP] MetroLog 추가하기  (0) 2018.04.21
제네릭 클래스(C# 프로그래밍 가이드)  (0) 2018.04.20
C# 5.0 || await || async  (0) 2018.04.19
C# version  (0) 2018.04.19
Mutex 클래스  (0) 2018.04.19

+ Recent posts