D.Costa D.Costa - 4 months ago 17
C# Question

Call successively an async method and sync method

I have an async method that query data from a MySql server and write them in a txt file. (I didn't find a way to return a string from an async method).

And then, I have to call a simple sync method that read the txt file.

My code looks like :

var sql = new ProjetTN.Class.SQLite();
sql.GetSens("101"); //<--- This is an async method

var SensItems = sql.ListeSens(); //<--- This method return a List<string>


But if I run the code like that, the async method will be skip and will not write the txt file. After that the sync method will be try to read the txt file but he doesn't exists, so the program will crash.

In my research, I found that I need to wait for the async method be complete so I tried :

public void CallGetSens()
{
var task = GetSens("101");
task.Wait();
}


When I call the methods :

var sql = new ProjetTN.Class.SQLite();
sql.CallGetSens(); //<--- This is an async method

var SensItems = sql.ListeSens(); //<--- This method return a List<string>


But this just freeze the program...

So how can I call successively an async method an then a sync method ?
Otherwise, how can I return a string from an async method ?

Answer

The best way is usually to make the method that's doing the calling be async so that you can await the async call:

async Task MyMethod()
{
    var sql = new ProjetTN.Class.SQLite();
    await sql.CallGetSens(); 

    var SensItems = sql.ListeSens();
    ...
}

If that won't work for some reason, you can use .ContinueWith() to make the loading of data from the text file happen after the file has been saved:

var sql = new ProjetTN.Class.SQLite();
sql.CallGetSens().ContinueWith(t => {
    var SensItems = sql.ListeSens();
    ...
});
Comments