Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7014999
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T22:35:43+00:00 2026-05-27T22:35:43+00:00

I have two threads that are declared global.On the form load i start the

  • 0

I have two threads that are declared global.On the form load i start the two threads.On the exit button click i am trying to abort these two threads if they are alive or else join.But i get this error “Attempted to read write protected memory” and the applications hangs sometimes.In one thread i am creating a pipe and waiting for connection in a while loop and in the other thread i am updating a datagrid on the background form.

Any ideas what is happening.I can post the code if my question is not clear enough but the code is very big.

Thanks

The code for form load is

private void frmStatus_Load(object sender, EventArgs e)
{
    Control.CheckForIllegalCrossThreadCalls = false;
    RefreshStatus = new Thread(RefreshStatusForm);
    RefreshStatus.IsBackground = true;
    RefreshStatus.Start();

    th = new Thread(this.CreatePipe);
    th.IsBackground = true;
    th.Start();
}

The code for closing the form is on a button click

private void btnOk_Click(object sender, EventArgs e)
{
    try
    {
        System.Object lockThis = new System.Object();

        lock (lockThis)
        {
            bCheckVal = false;

            if (!this.bComplete)
                stopOperation();

            Thread.Sleep(1000);

            ////////These are the lines in which i get the error 
            if (!th.IsAlive) 
            {
                th.Join();
            }
            else
            {
                th.Abort();
            }

            this.bRefresh = false;
            Thread.Sleep(1000);
            if (RefreshStatus.IsAlive)
            RefreshStatus.Abort();
            else
            RefreshStatus.Join();

            /////////////////
            this.bFlag = true;
        }

        this.Close();           
    }
    catch (System.Exception ex)
    {
    }
}

The code which is executed by the threads

        public  void CreatePipe()
    {
        try
        {
            PipeSecurity pipeSa = new PipeSecurity();
            pipeSa.SetAccessRule(new PipeAccessRule("Everyone",
                            PipeAccessRights.ReadWrite, AccessControlType.Allow));

            NamedPipeServerStream pipeServer = new NamedPipeServerStream(
                this.strguid,                    // The unique pipe name.
                PipeDirection.InOut,            // The pipe is bi-directional
                NamedPipeServerStream.MaxAllowedServerInstances);

            string strMessage = string.Empty;
            char[] bRequest = new char[BUFFER_SIZE];// Client -> Server
            int cbBytesRead, cbRequestBytes;
            StreamReader sr = null;
            byte[] bReply;                          // Server -> Client
            int cbBytesWritten, cbReplyBytes;
            int icount = 0;
            List<string> lsRead = new List<string>();
            cbBytesRead = 0;
            CopyFileThread = new Thread(this.CopyFile);
            CopyFileThread.IsBackground = true;
            CopyFileThread.Start();
            bool bflag = false;


            while (true)
            {
                this.bComplete = false;
                bWait = true;

                try
                {




                    pipeServer.WaitForConnection();

                    sr = new StreamReader(pipeServer);

                    //string message = sr.ReadToEnd();
                    bWait = false;
                    cbRequestBytes = BUFFER_SIZE;






                    string pipeData = string.Empty;

                    pipeData = sr.Read(bRequest, 0, 255).ToString().Trim();
                    strMessage = new string(bRequest);




                    strMessage = strMessage.Replace("\0", string.Empty);
                    if (strMessage.Contains("Aborted"))
                    {


                        if (pipeServer.IsConnected)
                        {
                            pipeServer.Flush();
                            pipeServer.Disconnect();
                        }
                        break;
                    }
                    else
                        if (strMessage.Contains("Completed"))
                        {
                            if (progressBar1.InvokeRequired)
                            {
                                strPercent = "100%";
                            }


                            if (pipeServer.IsConnected)
                            {
                                pipeServer.Flush();
                                pipeServer.Disconnect();
                            }
                            this.bComplete = true;
                            break;
                        }
                    // 26 dec 2011 Comment code //////
                    if (strMessage == "")
                    {
                        progressBar1.Visible = false;
                        progressBar2.Visible = true;
                    }
                    else
                    {
                        progressBar1.Visible = true;
                        progressBar2.Visible = false;
                    }

                    //// 26 dec 2011 Comment code //////

                    string[] strStatusMessages = strMessage.Trim().Split(',');



                    // 26 dec 2011 Comment code //////
                    pipeServer.Flush();

                    pipeServer.Disconnect();



                }
                catch (System.Exception ex)
                {
                    //MessageBox.Show(ex.ToString());

                }
            }


            pipeServer.Close();


            if (CopyFileThread.IsAlive)
                CopyFileThread.Abort();
            else
                CopyFileThread.Join();


            MessageBox.Show("Exiting from createpipe 2 Thread :{0}", Thread.CurrentThread.ToString());
            return;
        }
        catch (Exception ex)
        {
            return;
        }
    }

//////////////////////////////

void RefreshStatusForm()
{

        while (bRefresh)
        {
            if (iRefresh == 1)
            {
                GetRefresh();
                iRefresh = 0;
            }
            else if (iRefresh == 2)
                break;
            Thread.Sleep(1000);
        }

        MessageBox.Show("Exiting from RefreshStatusForm 2 Thread :{0}", Thread.CurrentThread.ToString());
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T22:35:44+00:00Added an answer on May 27, 2026 at 10:35 pm

    You don’t need to abort or join the thread. It is better to just let them finish normally. In your thread that does “waiting for connection in a while loop” have the while loop condition set as a bool and when you exit the program set the bool to false. Do something similar with the other thread as well.

    EDIT1
    So first of all:

    while (true)
                {
                    this.bComplete = false;
                    bWait = true;
    
                    try
                    {
    

    instead should be something like

    while(Running) {
    

    You use

    pipeServer.WaitForConnection(); 
    

    which is going to block the thread so I would change it an async task

        BeginWaitForConnection(
        AsyncCallback callback,
        Object state
    )
    

    but if you do not want to do that then add a timeout every so often.

    Then in

    void btnOk_Click
    

    all you need to do is set

    Running = false;
    bRefresh = false; 
    

    then the threads will finish themselves.

    EDIT2

    Set it up by using:

    AsyncCallback myCallback = new AsyncCallback(AsyncPipeCallback);  
    pipeServer.BeginWaitForConnection(myCallback, null); 
    

    Add this method:

    private void AsyncPipeCallback(IAsyncResult Result)  
    {   
        try  
        {  
            pipeServer.EndWaitForConnection(Result);  
                sr = new StreamReader(pipeServer);
    
                        //string message = sr.ReadToEnd();
                        bWait = false;
                        cbRequestBytes = BUFFER_SIZE;
    
    
    
    
    
    
                        string pipeData = string.Empty;
    
                        pipeData = sr.Read(bRequest, 0, 255).ToString().Trim();
                        strMessage = new string(bRequest);
    
    
    
    
                        strMessage = strMessage.Replace("\0", string.Empty);
                        if (strMessage.Contains("Aborted"))
                        {
    
    
                            if (pipeServer.IsConnected)
                            {
                                pipeServer.Flush();
                                pipeServer.Disconnect();
                            }
                            break;
                        }
                        else
                            if (strMessage.Contains("Completed"))
                            {
                                if (progressBar1.InvokeRequired)
                                {
                                    strPercent = "100%";
                                }
    
    
                                if (pipeServer.IsConnected)
                                {
                                    pipeServer.Flush();
                                    pipeServer.Disconnect();
                                }
                                this.bComplete = true;
                                break;
                            }
                        // 26 dec 2011 Comment code //////
                        if (strMessage == "")
                        {
                            progressBar1.Visible = false;
                            progressBar2.Visible = true;
                        }
                        else
                        {
                            progressBar1.Visible = true;
                            progressBar2.Visible = false;
                        }
    
                        //// 26 dec 2011 Comment code //////
    
                        string[] strStatusMessages = strMessage.Trim().Split(',');
    
    
    
                        // 26 dec 2011 Comment code //////
                        pipeServer.Flush();
    
                        pipeServer.Disconnect();
    
    
        }  
        catch { }
        if(Running)
            pipeServer.BeginWaitForConnection(myCallback, null); 
    } 
    

    Now when a connection occurs AsyncPipeCallback is called. Then when it finishes it check to see if it is still Running if it is it BeginWaitForConnection again.

    In btnOk_Click change it to this:

    private void btnOk_Click(object sender, EventArgs e)
    {
        try
        {
            System.Object lockThis = new System.Object();
    
            lock (lockThis)
            {
                bCheckVal = false;
    
                if (!this.bComplete)
                    stopOperation();
    
                Thread.Sleep(1000);
    
                Running  = false;
                bRefresh = false;
    
                this.bFlag = true;
            }
    
            this.Close();           
        }
        catch (System.Exception ex)
        {
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Suppose I have two threads A and B that are both incrementing a ~global~
I have two threads, a producer thread that places objects into a generic List
I have an application that has two threads. The first one (the main thread)
I have some code that will be accessed from two threads: class Timer{ public:
I have two threads, one that dispatches messages and another that parses them. Simple,
I have two threads. One invokes the update method of a class that modifies
I have two threads in haskell that perform IO. (They print only). Something like
I have a List and two threads that using the List. The first thread
I have a program (time lapse maker) which has two threads that updates a
I have two threads that use an event for synchronization. In each thread they

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.