使用Action with Task - 不确定它是如何工作的

Ero*_*ocM 1 c# delegates action task

我需要为我的应用程序创建一个单独的线程来记录一些事情,并建议我使用Task.

我似乎没有这个权利,因为我不完全理解任务(我猜).

这是我有的:

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);
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?我没有得到任何错误,但是再次,我没有得到任何日志.

谢谢!

Ser*_*rvy 5

new Task(action); 创建一个新任务,但它不会做任何导致它实际执行的事情.

在这种情况下,您可以使用:

Task.Factory.StartNew( () => { /* code goes here */ });
Run Code Online (Sandbox Code Playgroud)

值得一提的是,如果您的代码特别短,那么创建/调度任务的开销可能比直接实际运行它的速度慢(这当然取决于代码是什么).还要确保在多线程环境中记录事件时,错误日志记录将正常工作.如果没有,您可以决定不打扰,或添加显式锁定.