Programing/C#

c# 크로스 스레드, 델리게이트 delegate 활용

Sang12 2015. 1. 5. 12:14

        public ServerMain()
        {
            InitializeComponent();
            Thread ServerMain = new Thread(Server_MainLoof);
            ServerMain.Start();
        }

 

 

private void Server_MainLoof()  //서버의 메인루프
{

            CheckForIllegalCrossThreadCalls = false;

            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, Constants.Server_Port);                             

 //서버의 아이피와 객체를 담기위한 객체


            ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);  

 //서버소켓 생성


            ServerSocket.Bind(ipep);  // bind
            ServerSocket.Listen(20);  // listen

 

sLog.AppendText("ip:    " + ipep.Address + "    port:   " + ipep.Port + "   Server Start....");

 

 

            while (true)
            {
                Accept_Client(ServerSocket);

            }

}

 

이런식으로 네트워크 프로그래밍을 하고 있었는데  sLog.AppendText 이 부분에서 크로스 스레드 에러가 발생한다.

크로스 스레드 에러란 메인 스레드에서 만들어진 ui가 메인 스레드외에 다른 스레드에서 접근할경우 발생하는 에러이다.

이럴경우는

 

 private delegate void Delegate(string sData);  

       

 private void DelegateFunction(string sData)
 {
            sLog.AppendText(sData);
 }

 

 델리게이트를 선언 해 주고

 this.Invoke(new Delegate(DelegateFunction), "hello");

델리게이트로 값을 넘겨 주어서 해결 하면 된다.

그 외에 간단하게 해결 하는 방법은

 this.Invoke(new MethodInvoker(
                delegate()
                {
                    sLog.AppendText("hello");
                }
            )
            );

이런식으로 MethodInvoker를 이용해 델리게이틀르 연결 하는 방법 인데 이 방법은 너무 많이 쓰면 소스가 지저분해지는 것 같다