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 8020137
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T21:36:08+00:00 2026-06-04T21:36:08+00:00

I’m currently having a problem, which seems to be related to closing a Form,

  • 0

I’m currently having a problem, which seems to be related to closing a Form, while a scale, which is connected through a Serial Connection keeps sending data (about 3 packages per sek).

I handle new data over the DataReceived-Event (handling itself might be uninteresting for this issue, since I’m just matching data) Keep an eye on the COM_InUse variable and the allowFireDataReceived check.):

    private void COMScale_DataReceived(object sender, EventArgs e)
    {
        if (allowFireDataReceived)
        {
            //set atomar state
            COM_InUse = true;

            //new scale:
            if (Properties.Settings.Default.ScaleId == 1)
            {
                strLine = COMScale.ReadTo(((char)0x2).ToString());
                //new scale:
                Regex reg = new Regex(Constants.regexScale2);
                Match m = reg.Match(strLine);
                if (m.Success)
                {
                    strGewicht = m.Groups[1].Value + m.Groups[2];
                    double dblComWeight;
                    double.TryParse(strGewicht, out dblComWeight);
                    dblScaleActiveWeight = dblComWeight / 10000;
                    //add comma separator and remove zeros
                    strGewicht = strGewicht.Substring(0, 1) + strGewicht.Substring(1, 2).TrimStart('0') + strGewicht.Substring(3);
                    strGewicht = strGewicht.Insert(strGewicht.Length - 4, ",");

                    //write to textbox
                    ThreadSafeSetActiveScaleText(strGewicht);

                    COMScale.DiscardInBuffer();
                    //MessageBox.Show(dblScaleActiveWeight.ToString(), "dblScaleActiveWeight");
                }

            }
            //free atomar state
            COM_InUse = false;
        }
    }

The COM_InUse variable is a global bool and “tells” if there is a current process of handling data.
The allowFireDataReceived is also a global bool and if set to false will lead to no extra handling of the data which has been sended.

My problem now is the following:

It seems that Eventhandling is a separate Thread, which leads to a deadlock on klicking the Cancel-Button since the COM_InUse will never turn to false, even if the Event was handled (see end of COMScale_DataReceived, where COM_InUse is set to false).
While setting allowFireDataReceived = false works perfectly (no handling any more), as I said: the while loop will not terminate.

    private void bScaleCancel_Click(object sender, EventArgs e)
    {
        allowFireDataReceived = false;
        while (COM_InUse)
        {
            ;
        }
        if (!COM_InUse)
        {
            ret = 1;
            SaveClose();
        }
    }

When I comment out the while-block I have to click twice on the button, but it works without a crash. Since this very user unfriendly, I’m searching for an alternative way to safely close the window.

Info:
Simply closing (without checking if the COM-Data was processed) lead to a fatal crash.

So, maybe someone can explain to me what exactly causes this problem or can provide a solution to this. (Maybe one would be to trigger the Cancel-Clicking Event again, but that is very ugly)

Greetings!

I count on you 🙂

//edit:
Here is the current code of

    private void ThreadSafeSetActiveScaleText(string text)
    {
        // InvokeRequired required compares the thread ID of the
        // calling thread to the thread ID of the creating thread.
        // If these threads are different, it returns true.
        if (this.lScaleActive.InvokeRequired)
        {   
            SafeActiveScaleTextCallback d = new SafeActiveScaleTextCallback(ThreadSafeSetActiveScaleText);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            this.lScaleActive.Text = text;
        }
    }
  • 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-06-04T21:36:10+00:00Added an answer on June 4, 2026 at 9:36 pm
       ThreadSafeSetActiveScaleText(strGewicht);
    

    Yes, the DataReceived event runs on a threadpool thread. You already knew that, you wouldn’t have called it “ThreadSafe” otherwise. What we can’t see is what is inside this method. But given the outcome, it is highly likely that you are using Control.Invoke().

    Which is going to cause deadlock when you loop on COM_InUse in code that runs on the UI thread. The Control.Invoke() method can only complete when the UI thread has executed the delegate target method. But the UI thread can only do that when it is idle, pumping the message loop and waiting for Windows messages. And invoke requests. It cannot do this while it looping inside the Click event handler. So Invoke() cannot complete. Which leaves the COM_InUse variable for ever set to true. Which leaves the Click event handler forever looping. Deadlock city.

    The exact same problem occurs when you call the SerialPort.Close() method, the port can only be closed when all events have been processed.

    You will need to fix this by using Control.BeginInvoke() instead. Make sure the data is still valid by the time the delegate target starts executing. Pass it as an argument for example, copying if necessary.

    Closing the form while the scale is unrelentingly sending data is in general a problem. You’ll get an exception when you invoke on a disposed form. To fix this, you’ll need to implement the FormClosing event handler and set e.Cancel to true. And unsubscribe the DataReceived event and start a timer. Make the Interval a couple of seconds. When the timer Ticks, you can close the form again, now being sure that all data was drained and no more invokes can occur.

    Also note that calling DiscardInBuffer() is only good to randomly lose data.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a text area in my form which accepts all possible characters from
I am currently running into a problem where an element is coming back from
I am trying to understand how to use SyndicationItem to display feed which is
I used javascript for loading a picture on my website depending on which small
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I want use html5's new tag to play a wav file (currently only supported
I would like to run a str_replace or preg_replace which looks for certain words
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build

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.