简体   繁体   中英

How do i run a program or function when my main program ends in C#

I am new to windows development and I need that.

In php I can do like that:

<?php

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

?>

When I do that the php program call the second.sh program to run and exit without waiting the second.sh exit

I need this behavior in c# program

My second program will run for 5 minutes and exit. I need to make a POST, but I do not want to wait the request to finish to continue the main program, because this request can take 5 min to finish.

Run another program is a 'workaround' I saw on php. The ideal would be call a HttpWebRequest and do not wait it to finish.

The short answer

You can launch another process like this:

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

Taken from this answer . The program needs to be on your PATH so that you can run it by name like that. Otherwise you'll need to specify its full file path.

However

You could do all of this in one program if you wanted:

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
}

I don't know how your second program checks for the POST response, but whatever it is, you could replicate that logic in GetResponse.

"The ideal would be call a HttpWebRequest and do not wait it to finish."

You can do TaskFactory.StartNew(() => Something.HttpWebRequest("url"));

Thanks everyone I end up with that:

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

};

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

th.Start();

For some reason the TaskFactory.StartNew did not run my slowFunction:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM