Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Threading in a method

I have the following method :

public List<string> someMethod()
{

   // populate list of strings
   // dump them to csv file
   //return to output
}

Question is: i dont want the user to wait for csv dump, which might take a while. If i use a thread for csvdump, will it complete? before or after the return of output?

After csvdump is finished, i d like to notify another class to process the csv file. someMethod doesnt need to wait for csvdump to finish ?

like image 488
DarthVader Avatar asked Apr 03 '10 15:04

DarthVader


3 Answers

This is an excellent article on C# threading that anyone wanting to know about C# Threading should read.

But for your situation I would do something like this:

class Program {
  static BackgroundWorker bw;
  static void Main() {
    bw = new BackgroundWorker();
    bw.WorkerSupportsCancellation = true;
    bw.DoWork += bw_DoWork;
    bw.RunWorkerCompleted += bw_RunWorkerCompleted;

    bw.RunWorkerAsync ();
  }

  static void bw_DoWork (object sender, DoWorkEventArgs e) {
    //Run your code here
  }

  static void bw_RunWorkerCompleted (object sender, RunWorkerCompletedEventArgs e) {
    //Completed
  }
}

If the process is likely to take some time you can get the BackgroundWorker to report it's progress too.

like image 177
Chris Avatar answered Nov 04 '22 21:11

Chris


If you don't want the user to wait for the operation to complete that's call an asynchronus call.

Asynchronus calls follow a pattern in .NET that I suggest you use.

This kind of calls involve (usually) using the ThreadPool to perform the action in the background and then invoking a given callback when the action is complete. You can do something in this callback (that is executed by the thread).

This model requires the user to know that the process is asynchronus. That's actually a good thing for 99% of the cases because you need to be able to tell the calling code that the task is not don't yet, you return the control inmediatly but that doesn't mean the work has been completed.

like image 25
Jorge Córdoba Avatar answered Nov 04 '22 20:11

Jorge Córdoba


If you are doing this from a WinForms or WPF UI, you can use a BackgroundWorker to do the CVS dump, which can do the work in a background thread, and send an event to the UI when it is complete.

like image 22
Justin Ethier Avatar answered Nov 04 '22 22:11

Justin Ethier