Application/C# (WinForm)

[C# WinForm] Delegate, Event, Invoke, Cross Thread 사용법

devsalix 2022. 12. 1. 16:45
728x90

Main Form 외 다른 Class 선언 후 해당 클래스에 추가 Thread로 동작을 하고 있을 시

 

Main Form의 컨트롤을 제어하고 싶다면

 

아래처럼 코드를 설계하면 Cross Thread 오류가 나지 않는다

 

Class 영역
public class MainModule
{
	public delegate void _Delegate(string strMsg);
	public event _Delegate EventDelegate;

	private Thread m_h1;

	public MainModule()
	{
		
	}
    
	public bool ServerStart()
	{
		m_h1 = new Thread(new ThreadStart(Proc));
		m_h1.Start();
	}
	
	public void ServerStop()
	{
		m_h1.Abort();
		m_h1.Join();
	}
		
	public void Proc()
	{
		bool bRun = true;

		do
		{
			try
			{
				//....
			}
			catch (Exception Ex)
			{
				//...
				
				//오류 발생
				EventDelegate(Ex.Message);
                
				bRun = false;
			}
			finally
			{
				//...
			}
		} while (bRun);
	}
}

 

Form 영역
private MainModule m_MainModule;

private void Form1_Load(object sender, EventArgs e)
{
	m_MainModule = new MainModule();
	m_MainModule.EventDelegate += new MainModule._Delegate(m_MainModule_EventDelegate);
}

private void m_MainModule_EventDelegate(string strMsg)
{
	if (textBox1.InvokeRequired)
	{
		textBox1.BeginInvoke(new MethodInvoker(delegate()
		{
			textBox1.Text = "Invok Test...";
		}));
	}
}
728x90
반응형