[英]How do i run a program or function when my main program ends in C#
我是Windows開發的新手,我需要這個。
在PHP中,我可以這樣:
<?php
exec("second.sh > /dev/null 2>&1")
?>
當我這樣做時,php程序將調用second.sh程序以運行和退出,而無需等待second.sh退出
我在C#程序中需要這種行為
我的第二個程序將運行5分鍾並退出。 我需要進行POST,但我不想等待請求完成才能繼續執行主程序,因為此請求可能需要5分鍾才能完成。
運行另一個程序是我在php上看到的“解決方法”。 理想的方法是調用HttpWebRequest,不要等待它完成。
您可以啟動另一個過程,如下所示:
using System.Diagnostics; // This goes in your usings at the top
...
Process.Start("process.exe");
取自這個答案 。 該程序必須位於您的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中復制該邏輯。
“理想的情況是調用HttpWebRequest,不要等待它完成。”
您可以執行TaskFactory.StartNew(()=> Something.HttpWebRequest(“ url”));
謝謝大家,我最后這樣說:
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
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.