Click here to Skip to main content
11,632,571 members (81,384 online)
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#
HI everyone...
when I close my application, it always stays with the active processes, each time I remove it from task manager, what do I do?

this is class listen
class Listener
    {
        
        public delegate void lbconnection(string lbconnection);
        public lbconnection lbc;
        Thread thdsHandler;
        public int lport;
        public string lpath;
        
        //Le constructeur de la class Listener
        public Listener(int port,string path,lbconnection lbcc)
        {
            lbc=lbcc;
            lport = port;
            lpath = path;
        }
        public TcpClient handlerSocket;
        public TcpListener tcpListener;
        public void listenerThread()
        {
            //la port d'coute initialisé a 0   
            //int port = 0;
            //la creation de la class tcplistener 
            tcpListener = new TcpListener(new IPEndPoint(IPAddress.Any, lport)); 
            //le debut de l'ecoute on utilisant la methode start
            tcpListener.Start();
            //boucle infini while
            while (true)
            {
                //la method acceptsocket accept chaque client arrivé 
                handlerSocket = tcpListener.AcceptTcpClient();
                if (handlerSocket.Connected)
                {
                    lbc("Connected To Localhost :" + lport + " connected.");
                    //lbConnections.Items.Add("Connected To Localhost :" + lport + " connected.");
                    //lock pour ivite le blocage des clients
                    lock (this)
                    {
                        //alSockets.Add(handlerSocket);
                        Request rqs = new Request(lpath, handlerSocket);
                        //creation d'une thread appeler thdstHandler
                        thdsHandler = new Thread(new ThreadStart(rqs.handlerThread));
                        //thdHandler = new Thread(thdsHandler);
                        //le debut de travail de thread thdstHandler,on utilisant la methode start
                        thdsHandler.Start();
                    }
                }
            }
        }
        //procedure killthread
        public void killthread()
        {
         thdsHandler.Abort();
        }
    }

and the request class

class Request
    {
        //public delegate void Desplaylist(string lv0, string lv1, string lv2, string lv3, string lv4);
        //Desplaylist ds;
        //int tcn = 0; int cc = 0; int sr = 0; int fr = 0; int mc = 0; int rs = 0;
        //public Thread thdHandler;
        //Listener lst;
        public string tbpath;
        public TcpClient tcpclient;
        public Request(string tbpath, TcpClient tcpclient)
        {
           this.tbpath = tbpath;
           this.tcpclient = tcpclient;  
        }
        
 
        public struct serverinfo
        {
            public string httpversion;
            public string Date;
            public string sinfo;
            public string AcceptRanges;
            public string ContentLength;
            public string Connection;
            public string ContentType;
        };
 
        // la procedure handleThread fait le traitement de requette arrivé de client 
        public void handlerThread()
        {
            //tcn++;
            //lbConnections.Items.Add("Server Started");
            byte[] clientData = new byte[1024];
            //initialisation d'une socket appele handlesocket 
            //Socket handlerSocket = (Socket)alSockets[alSockets.Count - 1];
            String filename = "";
            String[] verbs;
            NetworkStream ns = tcpclient.GetStream();
            ns.Read(clientData, 0, clientData.Length);
            //handleSocket.Receive(clientData);
            //maitre la requette recus dans un fichier text
            string stringdata = Encoding.ASCII.GetString(clientData);
            File.WriteAllText(tbpath + "\\Request.txt", stringdata);
            verbs = stringdata.Split(" ".ToCharArray());
            // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            filename = verbs[1].Replace("/", "\\");
            if (filename.IndexOf("?") != -1)
            {
                // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                filename = filename.Substring(0, filename.IndexOf("?"));
            }
            if (filename.EndsWith("\\"))
            {
                // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
                filename += "index.html";
            }
            filename = tbpath + filename;
            if (!File.Exists(filename))
            {
                //fr++;
                filename = tbpath + "\\Page Not Found.html";
            }
            //if (filename != "\\Page Not Found.html")
            //{
            //    sr++;
            //}
            //ds(Convert.ToString(tcn), Convert.ToString(cc), Convert.ToString(sr), Convert.ToString(fr), Convert.ToString(mc));
            //creation d'une nouvelle class filestream appele fs ouvrir ou cree le fichier ou lien filename
            FileStream fs = new FileStream(filename, FileMode.Open);
            //pointe sur le depart de string 
            fs.Seek(0, SeekOrigin.Begin);
            byte[] fileContents = new byte[fs.Length];
            //Maitre le contenu de (les bites) dans la variable filecontents
            fs.Read(fileContents, 0, (int)fs.Length);
            fs.Close();
            //envoy la reponce ou client on utilisons la methode Send 
            ns.Write(fileContents, 0, fileContents.Length);
            //handleSocket.Send(fileContents);
            serverinfo sinfo = new serverinfo();
            sinfo.httpversion = "HTTP/1.1 200 OK \r\n";
            sinfo.Date = "Dtae: ";
            sinfo.sinfo = "Server: HTTPServer/1 (Windows) HTTP/1.1 \r\n";
            sinfo.AcceptRanges = "Accept-Ranges: bytes \r\n";
            sinfo.ContentLength = "Content-Length: 1564 \r\n";
            sinfo.Connection = "Connection: Close \r\n";
            sinfo.ContentType = "Content-Type: text/html \r\n";
            string servinfo = sinfo.httpversion + sinfo.Date + DateTime.Now.Date + "," + DateTime.Now.Month + " " + DateTime.Now.Year + "  " + DateTime.Now.Hour + " " + DateTime.Now.Minute + " "
                + DateTime.Now.Second + "\r\n" + sinfo.sinfo + sinfo.AcceptRanges + sinfo.ContentLength + sinfo.Connection + sinfo.ContentType + "\r\n" + Encoding.ASCII.GetString(fileContents);
            File.WriteAllText("C:\\www\\Reponse.txt", servinfo);
            //lbConnections.Items.Add(filename);
            //arreté la socket
            ns.Close();
            //handleSocket.Close();
            //procedute killthread qui tue le Thread
            //lst.killthread();
        }
    }

and the click bouton

private void btnStart_Click(object sender, EventArgs e)
        {
 
            tbPort.ReadOnly = true;
            tbPath.ReadOnly = true;
            //la creation d'une list des socket
            int port = 0;
            port = Convert.ToInt16(tbPort.Text);
            string path = tbPath.Text;
            //alSockets = new ArrayList();
            Listener lst = new Listener(port, path, this.lbconnect);
            //creation d'une thread appeler thdlistener
            thdListener = new Thread(new ThreadStart(lst.listenerThread));
            //le debut de travail de thread...on utilisant la methode start
            thdListener.Start();
 
            ////////////////////////////////
            btnStart.Enabled = false;
            Resume.Enabled = false;
            Suspend.Enabled = true;
            Stop.Enabled = true;
        }

this is my work and i need to explain me the wrong ...
Posted 23-Apr-11 4:38am
Edited 24-Apr-11 7:51am
v2
Comments
SAKryukov at 24-Apr-11 13:52pm
   
I vote 1 for "remove application from processes". You don't want to "remove" any process, ever!
You need to fix the bug though...
--SA
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Do you have secondary threads that may still be alive? (if they are foreground threads, all of them need to terminate before the process terminates)

[Update]
-----------

Just an update. From the comments OP made, this was indeed the issue. He had to mark the threads as background threads and that fixed his problem.
  Permalink  
v3
Comments
guendouz bachir at 23-Apr-11 10:48am
   
yes i use thread in my aplication... what can i do?
Nishant Sivakumar at 23-Apr-11 10:50am
   
I guess you could change them to be background threads (as opposed to foreground threads).
Nishant Sivakumar at 23-Apr-11 10:51am
   
See http://msdn.microsoft.com/en-us/library/system.threading.thread.isbackground.aspx
guendouz bachir at 23-Apr-11 11:01am
   
an article explain it ? i will see msdn
Nishant Sivakumar at 23-Apr-11 11:03am
   
Yeah, read up on the IsBackground link I gave above.
guendouz bachir at 24-Apr-11 10:15am
   
ok i had fixed the problem thank you so much
Nishant Sivakumar at 24-Apr-11 10:17am
   
No problem.
SAKryukov at 24-Apr-11 14:06pm
   
I answered based on the code provided. Well, no wonder the process is not closed...
--SA
guendouz bachir at 25-Apr-11 7:19am
   
i have do this thdListener.IsBackground = true; and it worked perfectly, see the IsBackground property ....
Nishant Sivakumar at 25-Apr-11 8:57am
   
Yep, I know :-) I told you to do that a few comments above.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

You do a bad thing: you create threads in loop. For networking, you need either one thread (on client side) or two threads on server side: one is accepting new connections (adding info on remote thread to some container), another thread execute data exchange protocol: read/write from/to network stream. Also, don't use lock — socket is itself a thread synchronization primitive. You need to create thread(s) from the very beginning and abort them when you close the application.

Also, if you use Thread.Abort, you must process ThreadAbortException.

The number of threads should be fixed.

See my answer to a similar question where I describe the skeleton of right design:
Multple clients from same port Number[^].

You never want to "remove application from Processes (Task Manager)"!
You problem is the application which is not finished due to pending thread(s). One solution could be using thread pool — the unfinished threads will not prevent your process from closing. This won't be a resolution of the code problem, which is in the logic of your thread life-time control. I don't want to look for your bug, because you design looks wrong. You need to address the design using my directions above.

—SA
  Permalink  
Comments
Nishant Sivakumar at 24-Apr-11 14:06pm
   
Voted 5.
SAKryukov at 24-Apr-11 21:04pm
   
Thank you, Nishant.
--SA
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

Process[] Processes = Process.GetProcessesByName("name of process goes here");
            foreach (Process Proc in Processes)
            {
                Proc.Kill();
            }
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 OriginalGriff 8,498
1 Sergey Alexandrovich Kryukov 8,149
2 Mika Wendelius 6,260
3 F-ES Sitecore 2,321
4 Suvendu Shekhar Giri 1,995


Advertise | Privacy | Mobile
Web04 | 2.8.150728.1 | Last Updated 27 Apr 2011
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100