none
Thread and Task Issue RRS feed

  • Question

  • Hi,

    I want to achieve the http request with asynchronous thread.

    However I found that if it will block the main thread if I use Task in the new thread.

    This is the code I test in winform (I don't think it is the issue of winform, just test in winform)

     public partial class Form1 : Form
        {
            private delegate void TestDe();
            TestDe d;
            public Form1()
            {
                d = new TestDe(TGE2);
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                Thread s = new Thread(new ThreadStart(TGE));
                s.Start();
                
            }
            private void TGE()
            {
                Thread.Sleep(new TimeSpan(0, 0, 5));
                this.Invoke(d);
                
            }
             private void TGE2()
             {
                 MessageBox.Show("hello");
                 Task.WaitAll(PP());
             }
            private async Task PP()
             {
                 Thread.Sleep(new TimeSpan(0, 0, 5));
             }
        }

    1. First 5 sec, it won't block main thread, it will show hello.

    2. After that it will block the main thread!

    I don't know why. Please help.

    Thanks

    Starain


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Friday, November 7, 2014 9:47 AM

Answers

  • Control.Inovke will cause the method running at that control's thread.

    When your code runs to this.Invoke(d) , it run TGE2() Method in UI thread.


    在現實生活中,你和誰在一起的確很重要,甚至能改變你的成長軌跡,決定你的人生成敗。 和什麼樣的人在一起,就會有什麼樣的人生。 和勤奮的人在一起,你不會懶惰; 和積極的人在一起,你不會消沈; 與智者同行,你會不同凡響; 與高人為伍,你能登上巔峰。

    Friday, November 7, 2014 12:38 PM

All replies

  • Control.Inovke will cause the method running at that control's thread.

    When your code runs to this.Invoke(d) , it run TGE2() Method in UI thread.


    在現實生活中,你和誰在一起的確很重要,甚至能改變你的成長軌跡,決定你的人生成敗。 和什麼樣的人在一起,就會有什麼樣的人生。 和勤奮的人在一起,你不會懶惰; 和積極的人在一起,你不會消沈; 與智者同行,你會不同凡響; 與高人為伍,你能登上巔峰。

    Friday, November 7, 2014 12:38 PM
  • Hi Bill,

    Thanks.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Monday, November 10, 2014 1:31 AM