当我的主程序以C#结尾时,如何运行程序或函数?

时间:2016-04-29 13:12:07

标签: c# .net

我是Windows开发的新手,我需要它。

在php中,我可以这样做:

<?php

exec("second.sh > /dev/null 2>&1")

?>

当我这样做时,php程序调用second.sh程序运行并退出而不等待second.sh退出

我在c#program

中需要这种行为

我的第二个程序将运行5分钟并退出。 我需要发一个POST,但我不想等待请求完成继续主程序,因为这个请求可能需要5分钟才能完成。

运行其他程序是一种解决方法&#39;我在php上看到了。 理想的是调用HttpWebRequest并且不要等它完成。

3 个答案:

答案 0 :(得分:2)

简短回答

你可以启动另一个这样的过程:

using System.Diagnostics; // This goes in your usings at the top
...
Process.Start("process.exe");

取自this answer。该程序需要在您的PATH上,以便您可以按名称运行它。否则,您需要指定其完整文件路径。

然而

如果您愿意,可以在一个程序中完成所有这些:

public void Main()
{
    //Your main program

    // [Send the POST]

    // Now start another thread to wait for the response while we do other stuff
    ThreadPool.QueueUserWorkItem(new WaitCallback(GetResponse));

    //Do other stuff
    //...
}

private void GetResponse(object state)
{
    // Check for evidence of POST response in here
}

我不知道您的第二个程序如何检查POST响应,但不管它是什么,您都可以在GetResponse中复制该逻辑。

答案 1 :(得分:1)

“理想的是调用HttpWebRequest并且不要等待它完成。”

你可以做TaskFactory.StartNew(()=&gt; Something.HttpWebRequest(“url”));

答案 2 :(得分:0)

谢谢大家 我最终得到了:

System.Threading.ThreadStart th_start = () =>
{
    slowFunction(arg);

};

System.Threading.Thread th = new System.Threading.Thread(th_start)
{
    IsBackground = true
};

th.Start();

由于某种原因,TaskFactory.StartNew没有运行我的slowFunction:

Task.Factory.StartNew(() => 
   new MyApp().slowFunction(arg), 
   System.Threading.CancellationToken.None,
   TaskCreationOptions.None,
   TaskScheduler.Default
);
相关问题