3

I have three class, tow of them was UI class, in the mainForm class, I start a new form by execute

new LoginForm.ShowDialog();

in the LoginForm class, I write code about log in and log out, when the use loged in, I start a new thread to check if something need to be done,and update the databases; and here is the question, I don't know how to update a label that in the MainForm I search this question and they told me I should to use Delegate.but it really puzzled me a lot cause they don't in a same class so I don't know how to use Delegate cross thread and cross different Until now, my code is like this MainForm.cs:

public partial class MainForm : Form
        public delegate void testDelegate();
        public MainForm()
        {
            InitializeComponent();
        }
        public void msg(string s)
        {
            label.Test = s;
        }
}

LoginForm.cs:

JobDoer jD = new JobDoer();
Thread t2 = new Thread(new ThreadStart(jD.run));
t2.Start();

JobDoer:

public void run()
 {
     //tD();
     tD = new MainForm.testDelegate(MainForm.msg);
     //this.
     Thread.Sleep(1000);
     return;
}

what should I do next?

Menahem
  • 3,974
  • 1
  • 28
  • 43
Jason Young
  • 575
  • 3
  • 16
  • 4
    UI elements can be modified only by UI thread. So invoke UI thread using dispatcher from another thread when you need modification. – Leri Aug 12 '13 at 10:07
  • could you please give me some demo? – Jason Young Aug 12 '13 at 10:08
  • http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.aspx And depending what you use something should be holding property of this type that allows invoking UI thread. – Leri Aug 12 '13 at 10:10
  • See the answers to similar question: http://stackoverflow.com/questions/661561/how-to-update-the-gui-from-another-thread-in-c – Ryszard Dżegan Aug 12 '13 at 10:11

2 Answers2

0

Taken from: Best Way to Invoke Any Cross-Threaded Code?

You also could use an extension method and lambdas to make your code much cleaner.

using System.ComponentModel;
public static class ISynchronizeInvokeExtensions
{
  public static void InvokeEx<T>(this T @this, Action<T> action) where T : ISynchronizeInvoke
  {
    if (@this.InvokeRequired)
    {
      @this.Invoke(action, new object[] { @this });
    }
    else
    {
      action(@this);
    }
  }
}

So now you can use InvokeEx on any ISynchronizeInvoke and be able to access the properties and fields of implementing class.

this.InvokeEx(f => f.listView1.Items.Clear());
Community
  • 1
  • 1
bizzehdee
  • 20,289
  • 11
  • 46
  • 76
0

For this kind of thing theres the
System.ComponentModel.BackgroundWorker class. https://learn.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-implement-a-form-that-uses-a-background-operation. It handles the thread sync for you, plus it has a usefull prgress update event

Menahem
  • 3,974
  • 1
  • 28
  • 43