Note that there are some explanatory texts on larger screens.

plurals
  1. POInstantiating thread method from a different class in c#
    text
    copied!<p>Can someone point me how to deal with the following issue? Basically, im trying to reuse code from the following example found at: <a href="http://www.codeproject.com/KB/threads/SynchronizationContext.aspx" rel="nofollow">http://www.codeproject.com/KB/threads/SynchronizationContext.aspx</a> the only issue i dont understand is how i can instantiate the RUN method if it is found in a different class. Please see following code.</p> <pre><code>public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void mToolStripButtonThreads_Click(object sender, EventArgs e) { // let's see the thread id int id = Thread.CurrentThread.ManagedThreadId; Trace.WriteLine("mToolStripButtonThreads_Click thread: " + id); // grab the sync context associated to this // thread (the UI thread), and save it in uiContext // note that this context is set by the UI thread // during Form creation (outside of your control) // also note, that not every thread has a sync context attached to it. SynchronizationContext uiContext = SynchronizationContext.Current; // create a thread and associate it to the run method Thread thread = new Thread(Run); // start the thread, and pass it the UI context, // so this thread will be able to update the UI // from within the thread thread.Start(uiContext); } // THIS METHOD SHOULD GO IN A DIFFERENT CLASS (CLASS2) SO HOW TO CALL METHOD UpdateUI() private void Run(object state) { // lets see the thread id int id = Thread.CurrentThread.ManagedThreadId; Trace.WriteLine("Run thread: " + id); // grab the context from the state SynchronizationContext uiContext = state as SynchronizationContext; for (int i = 0; i &lt; 1000; i++) { // normally you would do some code here // to grab items from the database. or some long // computation Thread.Sleep(10); // use the ui context to execute the UpdateUI method, // this insure that the UpdateUI method will run on the UI thread. uiContext.Post(UpdateUI, "line " + i.ToString()); } } /// &lt;summary&gt; /// This method is executed on the main UI thread. /// &lt;/summary&gt; private void UpdateUI(object state) { int id = Thread.CurrentThread.ManagedThreadId; Trace.WriteLine("UpdateUI thread:" + id); string text = state as string; mListBox.Items.Add(text); } } </code></pre> <h2>EDIT:</h2> <p>for instance, the run method is given me by someone else (another developer) and i need to run this method as a different thread in my UI thread (Main Thread or class Form1), however, whenever i run the thread (run method) i also need to update a ListBox <code>mListBox</code> using the UpdateUI method.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload