Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Is it OK to call my method from any thread?

Posted on 2011-09-16
4
339 Views
Last Modified: 2012-08-13
I get the part about not updating the UI unless you're on the main thread.

My question now is: on line 39 of the sample code below, is it OK to call my LogMsg() method even though I may be running on a different thread?

namespace xyzzy
{
  public partial class Form1 : Form
  {
    // delegate enables asynchronous calls from other threads
    delegate void AppendTextBox1Delegate(string text);

    public Form1()
    {
      InitializeComponent();
    }

    /* Call this method to append text to textBox1 */
    public void AppendTextBox1(string text)
    {
      if (this.textBox1.InvokeRequired)  // Check if we are running on a different thread
      {
        // It's on a different thread, so use Invoke. (We call ourself through a delegate.)
        AppendTextBox1Delegate d = new AppendTextBox1Delegate(AppendTextBox1);
        this.textBox1.Invoke (d, new object[] { text });
      }
      else
      {
        // It's on the main UI thread, no need for Invoke
        this.textBox1.AppendText(text + Environment.NewLine);
      }
    }


    private void LogMsg(string text)
    {
      AppendTextBox1(text);
    }


    private void serialPort1_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
    {
      //I could be on any thread. Can I still call LogMsg?
      LogMsg("serialPort1_ErrorReceived.");
    }

  }
}

Open in new window

0
Comment
Question by:deleyd
  • 2
4 Comments
 
LVL 35

Accepted Solution

by:
Miguel Oz earned 250 total points
ID: 36552950
Yes it is OK, as you are using Invoke if you are calling this.textBox1.Invoke from a different thread.
If you a solution with anonymous methods, check:
http://stackoverflow.com/questions/2367718/c-automating-the-invokerequired-code-pattern
0
 
LVL 35

Assisted Solution

by:Miguel Oz
Miguel Oz earned 250 total points
ID: 36552973
Forgot to add this link:
http://msdn.microsoft.com/en-us/library/ms171728(v=vs.80).aspx
(see SetText method)
0
 
LVL 85

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 125 total points
ID: 36553065
Agreed...it's safe.  But why not call AppendTextBox1() directly?...
0
 
LVL 13

Assisted Solution

by:Corey2
Corey2 earned 125 total points
ID: 36553133
You might want to consider BeginInvoke if there is any chance that the update could cause a subsequent log message (shouldn't in your sample), it will also allow the logging to happen without stopping the calling thread to wait for the logging to finish.

this.textBox1.BeginInvoke (d, new object[] { text });
0

Featured Post

Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question