0973bc24a0231f6a7d24223f20975d60f3e100a1.svn-base 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9. namespace BEMSDataGateway
  10. {
  11. delegate void TestDelegate(string msg);
  12. delegate void TestDelegate2();
  13. public partial class Loading_Form : Form
  14. {
  15. public Loading_Form()
  16. {
  17. InitializeComponent();
  18. System.Threading.Thread thread = new System.Threading.Thread(Thread1);
  19. thread.Start();
  20. }
  21. private void Loading_Form_Load(object sender, EventArgs e)
  22. {
  23. }
  24. private void showText(string msg)
  25. {
  26. Loading_Point.Text = msg;
  27. }
  28. private void Thread1()
  29. {
  30. for (int i = 0; i < 101; i++)
  31. {
  32. //[증상]
  33. //Control.Invoke()를 이용하여 서로 다른 스레드의 컨트롤에 접근하고자 할때, 간헐적으로 아래에 예외가 발생할 수 있습니다.
  34. //[예외]
  35. //MainForm.WorkerThreadFunction|System.InvalidOperationException: 창 핸들을 만들기 전까지 컨트롤에서 Invoke 또는 BeginInvoke를 호출할 수 없습니다.
  36. //(Invoke or BeginInvoke cannot be called on a control until the window handle has been created)
  37. //[원인]
  38. //예외 메시지 그대로 핸들이 만들어 지기 전에 Invoke 메서드가 호출되기 때문.
  39. //[해결 방안]
  40. //아래와 같이 명시적으로 핸들 값을 변수에 할당함으로써, 이렇게 하면 내부적으로 핸들이 없는 경우 강제로 만들어 지도록 한 후에 Invoke를 호출한다.
  41. ForceToCreateHandle();
  42. this.Invoke(new TestDelegate(showText), i.ToString());
  43. System.Threading.Thread.Sleep(20);
  44. }
  45. this.Invoke(new TestDelegate2(Close));
  46. }
  47. private void ForceToCreateHandle()
  48. {
  49. IntPtr x;
  50. if (!this.IsHandleCreated)
  51. x = this.Handle;
  52. }
  53. }
  54. }