K
K
kykyryky2016-09-27 17:49:31
.NET
kykyryky, 2016-09-27 17:49:31

Why doesn't await wait for the previous await to complete?

There are 3 methods:
1. Reading from a file:

public Task LoadFromFileAsync()
        {
            return Task.Run(() =>
            {
                //загрузка данных из файла
            });
        }

2. Calculations. simultaneously launches 3 methods of various kinds of calculations:
public async Task StartCalculationAsync()
        {
            Task.Factory.StartNew(() => Calculation1());
            Task.Factory.StartNew(() => Calculation2());
            Task.Factory.StartNew(() => Calculation3());
        }

3. Saving results:
public Task SaveToFileAsync()
        {
            return Task.Run(() =>
            {
                SaveToFile();
            });
        }

In the event handler, they are called like this:
private async void button_Click(object sender, RoutedEventArgs e)
        {
            await LoadFromFileAsync(); //выполняется 10-15 секунд
            await StartCalculationAsync(); //может выполняться часами
            await SaveToFileAsync(); //выполняется 1-2 секунды
        }

LoadFromFileAsync is executed, StartCalculationAsync waits for LoadFromFileAsync to complete and then starts executing. But at the same time, SaveToFileAsync starts running. Why is this happening? After all, SaveToFileAsync must wait for StartCalculationAsync to complete.
And why the moderator removed the "Programming" tag. Is this not programming?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Peter, 2016-09-27
@kykyryky

Here

public async Task StartCalculationAsync()
{
            Task.Factory.StartNew(() => Calculation1());
            Task.Factory.StartNew(() => Calculation2());
            Task.Factory.StartNew(() => Calculation3());
}

you startanuli 3 threads, but you do not return the created Task objects. What should the program wait for?
Task.WaitAllhelp you

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question