-2

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

caesay
  • 16,932
  • 15
  • 95
  • 160
Maher HTB
  • 737
  • 3
  • 9
  • 23

1 Answers1

3

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.

TheLethalCoder
  • 6,668
  • 6
  • 34
  • 69
  • 1
    Right answer, it should be said, that using `async void` pattern means `fire and forget` call. If the method then fails (throws exception) - no one will know – Gh61 Apr 13 '17 at 10:02
  • @Gh61: `async void` methods will re-raise any exceptions on their `SynchronizationContext`, which in many cases crashes the process. I like to call these "fire and crash" rather than "fire and forget". – Stephen Cleary Apr 13 '17 at 11:40