【问题标题】:How to run Main() method from C# program in the thread pool?如何在线程池中从 C# 程序运行 Main() 方法?
【发布时间】:2014-01-03 14:04:24
【问题描述】:

我想知道,我怎样才能像在 F# 中那样在线程池中运行 C# 程序的方法 Main()

let main() =
    Console.WriteLine("Hello World!")

do Task.Factory.StartNew(main).Wait()

C# 编程语言中的替代代码是什么?因为在简单的控制台应用中,只有这样的使用方式:

static void Main() // or with int as the return type and args[]
                   // in method arguments but it's not important for this question

而且我不能像在 F# 中那样添加 smth:

do Task.Factory.StartNew(main).Wait()

或者我只是不知道 C# 程序执行的所有可能性?

【问题讨论】:

  • 您的 F# main 实际上并不相同 - F# 实际上创建了一个调用 do 的隐式函数。等效的方法是使用 [<Entrypoint>] 注释 F# 位
  • @JohnPalmer 是的,你是对的
  • 我认为完全放弃调用 Main 的想法可能是个好主意,如果您想递归调用它们,请使用其他函数。我一直认为 Main 风格不好。
  • 这完全没有意义。您只是在执行 Main 的原始线程正在等待时产生另一个线程。您不会从中获得任何好处,尤其是并发性或性能。你输了。
  • @usr - 这显然不是真正的(结束)代码。

标签: c# f# threadpool main


【解决方案1】:

我可以建议你不要这样做。我相当确定您应该编写其他函数,然后您可以根据需要将它们添加到线程池中。

在大多数编程语言中,调用 main 函数是一种不好的风格;如果您想这样做,请编写其他函数来完成您的工作。 基本上:

static void Function(){
    //Do stuff
}
static void Main(){
  TaskFactory.StartNew(Function).wait();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-14
    • 2013-03-16
    • 2013-05-16
    • 1970-01-01
    • 2013-03-03
    • 2015-07-24
    • 2015-10-28
    • 2015-09-08
    相关资源
    最近更新 更多