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

C# 윈도우 프로그램에서 쓰레드를 사용하였는데 쓰레드에서 폼의 컨트롤을 사용할 경우
크로스 스레드 작업이 잘못되었습니다. ‘…’컨트롤이 자신이 만들어진 스레드가 아닌 스레드에서 액세스되었습니다.’
에러가 발생한다.
쓰레드가 컨트롤에 접근할때 무언가 충돌로 인한 에러인듯 하다.

해결하기 위해 예를 들어 라벨 컨트롤이라던지 텍스트 박스 컨트롤을 사용한다 치면

먼저 딜리게이트 선언.
delegate void Ctrl_Involk (Control ctrl, string text);
public void setText(Control ctrl, string txtValue)
{
            if (ctrl.InvokeRequired)
{
Ctrl_Involk CI= new Ctrl_Involk (setText);
ctrl.Invoke(CI, ctrl, txtValue);
}
   else
{
ctrl.Text = txtValue;
}
}
요렇게 해주면 문제를 해결 할 수 있다.
만약 .Text 같은 일반적인 속성을 사용할것이 아니라고 한다면.. 예를 들어 ProgressBar 에 값을 셋팅하려고 한다면
인자에 Control 대신 System.Windows.Forms.ProgressBar int 값으로 넘겨줘서 사용한다. ^^;

스레드 – 컨트롤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

“스레드 – 컨트롤Invoke(동기), BeginInvoke(비동기)”의 44개의 댓글

  1. You made some good points there. I checked on the net for additional information about the issue and found most people
    will go along with your views on this website.

  2. That is really attention-grabbing, You are an excessively
    professional blogger. I have joined your rss feed and stay up for looking for extra
    of your magnificent post. Also, I have shared your website in my
    social networks

  3. Have you ever considered writing an ebook or guest authoring on other websites?

    I have a blog based upon on the same subjects you discuss and would really like to have
    you share some stories/information. I know my audience would value your
    work. If you’re even remotely interested, feel free to send me an email.

  4. Great beat ! I would like to apprentice whilst
    you amend your web site, how can i subscribe for a blog web site?
    The account helped me a acceptable deal. I had been a
    little bit familiar of this your broadcast provided vivid
    clear idea

  5. Can I just say what a relief to uncover a person that genuinely knows what they’re talking about over the internet.
    You definitely understand how to bring a problem to light and make it important.
    More and more people need to read this and understand this side of your story.
    I was surprised that you aren’t more popular because you definitely
    possess the gift.

  6. I just want to mention I am all new to blogging and site-building and definitely loved this web page. Almost certainly I’m want to bookmark your blog . You definitely have amazing articles and reviews. Thanks a bunch for sharing with us your website.

  7. I just couldn’t depart your site prior to suggesting that I extremely enjoyed the standard information an individual provide for your visitors? Is gonna be back frequently in order to inspect new posts

  8. There are some fascinating points in time in this short article but I don?t understand if I see every one of them center to heart. There is some legitimacy however I will certainly hold opinion up until I check out it better. Great write-up, many thanks and we desire more! Added to FeedBurner also

  9. Very good blog you have here but I was wondering if you knew of any user discussion forums that cover the same topics talked about here? I’d really love to be a part of group where I can get feed-back from other knowledgeable people that share the same interest. If you have any recommendations, please let me know. Thanks a lot!

  10. I’m impressed, I must say. Genuinely rarely do you encounter a weblog that’s both educative and entertaining, and let me tell you, you may have hit the nail about the head. Your concept is outstanding; ab muscles something that too few people are speaking intelligently about. I’m delighted i found this in my hunt for something about it.

  11. An intriguing conversation deserves comment. I assume that you need to write much more on this topic, it may not be a forbidden subject yet usually individuals are insufficient to talk on such topics. To the following. Cheers

  12. Nice post. I learn something harder on diverse blogs everyday. It will always be stimulating to learn to read content off their writers and use something at their store. I’d opt to apply certain while using the content in my small blog no matter whether you don’t mind. Natually I’ll offer you a link for your internet weblog. Appreciate your sharing.

  13. Aw, this was an actually wonderful blog post. In idea I want to place in composing such as this additionally? taking some time and also real initiative to make an excellent short article? however what can I claim? I procrastinate alot as well as by no means seem to get something done.

  14. When I initially commented I clicked the -Inform me when new remarks are included- checkbox as well as now each time a remark is added I obtain four e-mails with the exact same comment. Exists any way you can eliminate me from that solution? Thanks!

  15. There are certainly a lot of details like that to think about. That is a fantastic indicate raise. I supply the thoughts above as general inspiration but plainly there are questions like the one you bring up where the most vital point will certainly be operating in honest good faith. I don?t know if finest techniques have actually arised around points like that, however I am sure that your job is clearly recognized as a level playing field. Both kids as well as women feel the impact of just a moment?s enjoyment, for the remainder of their lives.

  16. Youre so amazing! I don’t mean Ive review anything similar to this prior to. So wonderful to locate someone with some original thoughts on this subject. realy thanks for starting this up. this website is something that is needed on the web, someone with a little creativity. helpful job for bringing something new to the web!

  17. After research a few of the article on your website currently, as well as I absolutely like your method of blog writing. I bookmarked it to my bookmark website listing and will be examining back soon. Pls have a look at my internet site as well as well as let me know what you believe.

  18. I uncovered your blog website on google and also examine a few of your early posts. Remain to keep up the great run. I simply extra up your RSS feed to my MSN Information Visitor. Looking for forward to reading more from you later on!?

  19. I?m pleased, I must claim. Really hardly ever do I experience a blog that?s both instructional and also amusing, and let me tell you, you have actually struck the nail on the head. Your suggestion is exceptional; the problem is something that insufficient people are talking intelligently around. I am really satisfied that I stumbled across this in my look for something relating to this.

  20. Nice article. I discover something extra difficult on different blogs day-to-day. It will constantly be boosting to review web content from other writers as well as practice a little something from their shop. I?d prefer to use some with the web content on my blog site whether you don?t mind. Natually I?ll provide you a web link on your internet blog site. Thanks for sharing.

댓글 남기기