Maher HTB Maher HTB - 8 months ago 35
C# Question

make a return function with await

Hi guys i did some code to get list of databases that exists in mongodb server.
the list is stored in lst i want to make the function give back a result so i used out .
here is the first method it works fine

public static async void listDatabases()
{
List<string> lst = null;
try
{
MongoClient client = new MongoClient("mongodb://127.0.0.1:27017");
//MongoServer server = client.GetServer();
// List<string> lstdatabases = server.GetDatabaseNames().ToList();
using (var cursor = client.ListDatabasesAsync())
{
await cursor.Result.ForEachAsync(d => lst.Add(d.GetElement(0).Value.ToString()));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}


and here what i tried to make the function return value

public static async void listDatabases(out List<string> lstListDB)
{
List<string> lst = null;
try
{
MongoClient client = new MongoClient("mongodb://127.0.0.1:27017");
//MongoServer server = client.GetServer();
// List<string> lstdatabases = server.GetDatabaseNames().ToList();
using (var cursor = client.ListDatabasesAsync())
{
await cursor.Result.ForEachAsync(d => lst.Add(d.GetElement(0).Value.ToString()));
lstListDB = lst;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
lstListDB = null;
}
}


it said i can't use out with async method any help thanks

Answer Source

You cannot use out in async methods as you have found. However, to return data from an async method simply have a return type of Task<T>. In your case:

public static async Task<List<string>> listDatabases()

Then you can just do the following in your method:

return lst;

You would then call it like:

var list = await listDatabases();

On a side note you should avoid a return type of void in async methods, instead you can use a return type of Task.