Java:
First, we need a class that implement Runnable interface.
public class FetchStockPrices implements Runnable{ public void run() { // Long running process goes in here!! // Retrieve stock price information from remote web service } }
Next, we instantiate the runnable class and pass it into the Thread constructor.
FetchStockPrices job = new FetchStockPrices(); Thread worker = new Thread(job);
Finally, we call the start() method of the Thread object. This will spawn a new thread from the executing thread and execute the target run() method defined in the runnable class.
worker.start();
Now, let’s take a look at the C# version. They are really similar.
C#:
First, we create a class that contain the long running method DoWork().
public class FetchStockPrices{ public void DoWork() { // Long running process goes in here!! // Retrieve stock price information from remote web service } }
Next, create the thread object, passing in the FetchSrockPrices.DoWork method via a ThreadStart delegate.
FetchStockPrices job = new FetchStockPrices(); Thread worker = new Thread(new ThreadStart(job.DoWork));
Finally, start the thread.
worker.Start();
Leave a comment