C # regularly return values ​​from another thread

I am very new to multithreading and no experience. I need to compute some data on another thread so the UI doesn't hang, then post the data as it is processed to a table in the main form. Thus, in principle, the user can work with data that has already been calculated, while other data is still being processed. What is the best way to achieve this? I would also be very grateful for any examples. Thanks in advance.

+2


a source to share


5 answers


If you don't want to use the Background Worker as KMan answered, you can create a thread yourself.



private void startJob(object work) {
    Thread t = new Thread(
      new System.Threading.ParameterizedThreadStart(methodToCall)
    );
    t.IsBackground = true; // if you set this, it will exit if all main threads exit.
    t.Start(work); // this launches the methodToCall in its own thread.
}

private void methodToCall(object work) {
    // do the stuff you want to do
    updateGUI(result);
}

private void updateGUI(object result) {
    if (InvokeRequired) {
        // C# doesn't like cross thread GUI operations, so queue it to the GUI thread
        Invoke(new Action<object>(updateGUI), result);
        return;
    }
    // now we are "back" in the GUI operational thread.
    // update any controls you like.
}

      

+2


a source


Check out this BackgroundWorker sample document .



+1


a source


Initialize your work object

BackgroundWorker bw = new BackgroundWorker(); 
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged); 

private void bw_DoWork(object sender, DoWorkEventArgs e) 
{ 
    // I need to compute some data in a different thread so the UI doesn't hang up
    // Well! ompute some data here.
    bw.ReportProgress(percentOfCompletion, yourData) // and then send the data as it is processed
    // percentOfCompletion-int, yourData-object(ie, you can send anything. it will be boxed)
}

private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e) 
{ 
     // to a table on the main form. So, basically, the user can work with the data that is already computed, while other data is still being processed
     List<string> yourData = e.UserState as List<string>; // just for eg i've used a List.
}

      

What is the best way to achieve this?

RunWorkerAsync(); //This will trigger the DoWork() method

      

+1


a source


Use a registry key to exchange data between threads

0


a source


You can send data to static variable, static variables are shared between threads.

-1


a source







All Articles