I need to create a separate thread for my application to log a few things and it was suggested to me to use Task.
I don’t seem to have this right since I don’t fully understand task (I guess).
Here is what I have:
public static void LogException(string message, Exception ex)
{
Action action= delegate() { logException(message, ex); };
new Task(action);
}
public static void logException(string message, Exception ex)
{
var stackTrace = new StackTrace();
var origin = stackTrace.GetFrame(1).GetMethod().Name;
var originclass = stackTrace.GetFrame(1).GetMethod().ReflectedType.Name;
var neworigin = string.Format("{0}.{1}", originclass, origin);
message += Environment.NewLine + Environment.NewLine + GetFullExceptionMessage(ex);
if (string.IsNullOrEmpty(message)) message = "No message given";
//var exceptions = GetAllErrMessages(ex);
//message = exceptions.Aggregate(message, (current, exception) => current + Environment.NewLine + exception);
EventLogging.LogEvent(neworigin, message, EventLogEntryType.Error, 9999);
EmailMessage(neworigin, message, EventLogEntryType.Error);
}
What am I doing wrong? I am not getting any errors but then again, I’m not getting any log.
Thanks!
new Task(action);creates a new task, but it doesn’t do anything that would result in it actually be executed.In this case, you can probably just use:
It’s worth mentioning that if your code is particularly short then the overhead of creating/scheduling the task might be slower than actually running it directly (this will of course depend on what that code is). Also make sure that your error logging will work properly when events are logged in a multithreaded environment. If not, you may either decide to not bother, or add explicit locking.