async & await problem in multi threads code

Ask a question
0

I have this simple situation:

public partial class Form1 : Form {
  Task t;
  public Form1() {
     InitializeComponent();
     t = Prepare();
  }

  public Task waitT() {
     return Task.Factory.StartNew(() => {
        for (int i = 0; i < 5; i++) {
           Thread.Sleep(1000);
           Console.WriteLine("T works \n");
        }
     });
  }
  public Task waitT2() {
     return Task.Factory.StartNew(() => {
        for (int i = 0; i < 3; i++) {
           Thread.Sleep(1000);
           Console.WriteLine("T2 works \n");
        }
     });
  }

  public Task waitT3() {
     return Task.Factory.StartNew(() => {
        for (int i = 0; i < 2; i++) {
           Thread.Sleep(1000);
           Console.WriteLine("T3 works \n");
        }
     });
  }

  public async Task Prepare() {
     //await Task.Factory.StartNew(async () => {
        await waitT();
        Console.WriteLine("T DOne.");
        await waitT2();
        Console.WriteLine("T2 DOne.");
        await waitT3();
        Console.WriteLine("T3 DOne.");
    // });
  }

  protected override void OnPaint(PaintEventArgs e) {
     base.OnPaint(e);
     t.Wait();
     Console.WriteLine("Finish");
  }
}

In a few words, i want start a task in constructor, and wait some data in Paint events. The problem is that the execution is blocked in wait() method and the code Console.WriteLine(“T DOne.”) is never called. I have read that the execution of asynch methods is in a first time synch and i think that the problem is this. To try to solve the problem i have changed my code of function prepare in this way:

 public async Task Prepare() {
     return await Task.Factory.StartNew(async () => {
        await waitT();
        Console.WriteLine("T DOne.");
        await waitT2();
        Console.WriteLine("T2 DOne.");
        await waitT3();
        Console.WriteLine("T3 DOne.");
     });
  }

In this way the situation change, and the wait method in paint is not respected, and the execution pass immediately to Console.WriteLine(“Finish”) and Prepare process is running to completition.

Probably i m committing a concectual error, someone can explain me the correct approach to do this?

Thanks

Coin iconoffer bounty
add comment

0 Answer

Your Answer