user1108948
user1108948

Reputation:

Exit a windows console application to clean up resources

I have a console application, in which I have a connection to a third party windows service on a remote server by tcp/ip.

The call Hierarchy likes:

static class Program
{
    [MTAThread]
    static void Main()
    {
        MyApplication.Start();

The Start method

public static void Start()
{
    lock (SyncVar)
    {
        ThreadStart ts = new ThreadStart(MainCode);
        MainCodeThread = new Thread(ts);
        MainCodeThread.IsBackground = false;
        MainCodeThread.Start();

The detail of main thread has:

private static void MainCode()
{
    try
    {
         // connect to the remote server, against a windows service 
         TelephonyServer tServer = new TelephonyServer(sIpaddress, "username", "password");
         while (true)
         {
            Task consumer = Task.Run(() =>
             {
                   if (data != "")
                   {
                        ProcessEachChannel(data);
            });

            Task producer = Task.Run(() =>
            {
                // blah blah
            });

In the method ProcessEachChannel, we have

    public bool ProcessEachChannel(string workItem)
    {
        ChannelResource cr = tServer.GetChannel();
        // blah blah
    }

Now the application is working well. However if I click the red exit cross of the application or click stop debugging button from Visual Studio, the resources ChannelResource cr is not destroyed at all. I found the fact from the remote server service control dashboard.

I tried some code

System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess(); process.Exited += new EventHandler(OnExited);

It is not helpful. I heard some tricks to manage the thread by passing parameters to the main thread then set something true or false etc but just no clue.

Upvotes: 1

Views: 2087

Answers (2)

ths
ths

Reputation: 2942

If you kill the process, instead of closing it gracefully (and that is what you do when you close the console window or press the stop buttpn in debugger), there's no chance for any cleanup code to run. you have to implement some exit handler, perhaps catching a ctrl-c press and then return from your threads, so all objects can cleanly dispose themselves.

Upvotes: 0

huysentruitw
huysentruitw

Reputation: 28091

The program will not exit until all running threads have been stopped.

Replace the while (true) in the thread code with while (!stopThread.WaitOne(10, false)) where stopThread is a WaitHandle like ManualResetEvent.

Then, when the application shuts down, Set the event and wait for the thread to exit.

Also note that some 3rd-party frameworks depend on Dispose being called on their object because they need to manage the lifetime of some separate threads they've spawned. F.e. read VoiceElements document and see how they call Disconnect and Dispose on a ChannelResource they've got from GetChannel(). Please check with the provider when and where you need to release used resources yourself.

Upvotes: 1

Related Questions