HaBo HaBo - 3 months ago 20
C# Question

Understanding Async Methods using C# 4.6.1

I have following Synchronous an Asynchronous methods

public static void Info(string message)
{
if (_logTypes.Contains(InfoLogType))
{
string applicationName, methodName, className;
ReflectClassAndMethod(out applicationName, out className, out methodName);
Write(applicationName, "Info", className, methodName, message);
}
}

public static async void InfoAsync(string message)
{
if (_logTypes.Contains(InfoLogType))
{
string applicationName, methodName, className;
ReflectClassAndMethod(out applicationName, out className, out methodName);
await WriteAsync(applicationName, "Info", className, methodName, message);
}
}


Further my Write Methods are like this

private static void Write(string applicationName, string logType, string className, string methodName, string message)
{
// construct me _event object
var collection = Database.GetCollection<Event>(typeof(Event).Name);
collection.InsertOne(_event);
}

private static Task WriteAsync(string applicationName, string logType, string className, string methodName, string message)
{
// construct my _event object
var collection = Database.GetCollection<Event>(typeof(Event).Name);
await collection.InsertOneAsync(_event);

}


using a test console app I call these synchronous and asynchronous method as bellow

static void Main(string[] args)
{
Log.Info("Synchronous write");
Log.InfoAsync(DateTime.Now.ToString(CultureInfo.InvariantCulture));
}


This will insert two documents to my Mongo Collection. but if I comment the synchronous call then nothing will be inserted.

static void Main(string[] args)
{
//Log.Info("Synchronous write");
Log.InfoAsync(DateTime.Now.ToString(CultureInfo.InvariantCulture));
}


This will insert nothing. Why is that?

Answer

Because your application terminates before the logger is finished.

You can simply await the call:

static void Main(string[] args)
{
  //Log.Info("Synchronous write");
  await Log.InfoAsync(DateTime.Now.ToString(CultureInfo.InvariantCulture));
}

Or, because this doesn't work in Main, read that: Can't specify the 'async' modifier on the 'Main' method of a console app

You can simply Log.InfoAsync(DateTime.Now.ToString(CultureInfo.InvariantCulture)).Wait();

Comments