-1

I am trying to fetch value from PORT where I attached hardware.I am successfully getting value from port but when I am trying to fill this value it gives following error

"the calling thread cannot access this object because a different thread owns it"

here is my code

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    try
    {
        string strAck = port.ReadExisting();

        if (!string.IsNullOrWhiteSpace(strAck))
        {
            txtvalue = strAck;            
        }
    }            
    catch(Exception ex)
    {    
    }
}
nathanchere
  • 8,008
  • 15
  • 65
  • 86
Sandip
  • 481
  • 1
  • 9
  • 26
  • 2
    Please see Related section on right hand side. This was answered many times before. – LPL Aug 27 '13 at 09:50
  • 1
    Also a little Google goes a long way. Often, I copy exception text directly to my search engine and only ask a question if i couldn't solve the problem that way. – Gusdor Aug 27 '13 at 10:02
  • If you are using .NET 4.5 try the new await and async api, it makes this problem much easier. http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx – sprocket12 Aug 27 '13 at 10:39

1 Answers1

0

You really should have searched for an answer to your problem before you posted this question, as it has been answered here many times before. The short answer is that you have to set the value on the UI thread. You would do that like this:

this.Dispatcher.Invoke((Action)(() =>
{
    string strAck = port.ReadExisting();
    if (!string.IsNullOrWhiteSpace(strAck))
    {
        txtvalue = strAck;            
    }
}));
Sheridan
  • 68,826
  • 24
  • 143
  • 183