Solved

Is it OK to call my method from any thread?

Posted on 2011-09-16
4
332 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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

929 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

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now