Álvaro García
Álvaro García

Reputation: 19356

Task isn't waited to finish and error timeout protocol error 2504

I have a class with this constructor:

MyType01 _myData01;
MyType02 _myData02;
MyType03 _myData03;


public MyClass()
{
    getDataFromDataBase();


    //Code that use the data from database.
    string myText = _myData02.Property1; //error because my data02 is null.
}


private async void getDataFromDataBase()
{
    await myMethod01Async();
    await myMethod02Async();
    await myMethod03Async();
}

This code works in a local database but when I connect to the database in a remote computer, I get an error of timeout and protocol 2504.

If I debug, I can notice that if I set a break-point in the line that run myMethod01Asyc() and press "F5", the next line of code is the next line in the constructor which try to use the data in _myData02 variable, but it is still null because it is not finished the method getMyData02Async().

Perhaps I am wrong, but I thought that using await the code wait until the method is finished, but in my case it isn't the behaviour because it continues with the next line in the constructor.

So how could I wait in the constructor until getDataFromDataBase() is finished to can use the data that I need?

Upvotes: 1

Views: 56

Answers (1)

Nkosi
Nkosi

Reputation: 247018

Avoid async void except for event handlers.

Reference Async/Await - Best Practices in Asynchronous Programming

I suggest you create an event handler and await you tasks there.

MyType01 _myData01;
MyType02 _myData02;
MyType03 _myData03;

public MyClass() {
    //subscribe to event
    LoadingData += OnLoadingData;
    //raise event
    LoadingData(this, EventArgs.Empty);
}

private event EventHandler LoadingData = delegate { };

private async void OnLoadingData(object sender, EventArgs args) {
    await getDataFromDataBase();
    //Code that use the data from database.
    string myText = _myData02.Property1; 
}

private async Task getDataFromDataBase() {
    await myMethod01Async();
    await myMethod02Async();
    await myMethod03Async();
}

Note the change of getDataFromDataBase to return a Task so that it can be awaited.

Upvotes: 3

Related Questions