How to spawn thread in C# - c#

Could anyone please give a sample or any link that describes how to spawn thread where each will do different work at the same time.
Suppose I have job1 and job2. I want to run both the jobs simultaneously. I need those jobs to get executed in parallel. how can I do that?

Well, fundamentally it's as simple as:
ThreadStart work = NameOfMethodToCall;
Thread thread = new Thread(work);
thread.Start();
...
private void NameOfMethodToCall()
{
// This will be executed on another thread
}
However, there are other options such as the thread pool or (in .NET 4) using Parallel Extensions.
I have a threading tutorial which is rather old, and Joe Alabahari has one too.

Threading Tutorial from MSDN!
http://msdn.microsoft.com/en-us/library/aa645740(VS.71).aspx

Threads in C# are modelled by Thread Class. When a process starts (you run a program) you get a single thread (also known as the main thread) to run your application code. To explicitly start another thread (other than your application main thread) you have to create an instance of thread class and call its start method to run the thread using C#, Let's see an example
using System;
using System.Diagnostics;
using System.Threading;
public class Example
{
public static void Main()
{
//initialize a thread class object
//And pass your custom method name to the constructor parameter
Thread thread = new Thread(SomeMethod);
//start running your thread
thread.Start();
Console.WriteLine("Press Enter to terminate!");
Console.ReadLine();
}
private static void SomeMethod()
{
//your code here that you want to run parallel
//most of the cases it will be a CPU bound operation
Console.WriteLine("Hello World!");
}
}
You can learn more in this tutorial Multithreading in C#, Here you will learn how to take advantage of Thread class and Task Parallel Library provided by C# and .NET Framework to create robust applications that are responsive, parallel and meet the user expectations.

Related

Is there a clean way of using Dispatcher in a .NET Console application?

In a .NET (C#) application I would like to have a dispatcher system, similar to dispatch_async() on iOS.
I read on multiple stackoverflow thread that Dispatcher should be used only in the context of a WPF application, but I don't understand why.
I wrote the following code by reading the MSDN documentation, and it is working.
Is there any reason why I should stop using that mechanism?
I don't want to realize later in the process that I am stuck because of something I did not know. (I am new to C# and .NET).
using System;
using System.Threading;
using System.Windows.Threading;
namespace ExcelLeak
{
class Program
{
public static Dispatcher mainSerialQueue;
public static Dispatcher backgroundSerialQeueue;
static void Main(string[] args)
{
mainSerialQueue = Dispatcher.CurrentDispatcher;
Thread serialQueueThread = new Thread(() =>
{
backgroundSerialQeueue = Dispatcher.CurrentDispatcher;
mainSerialQueue.BeginInvoke((System.Action)(() =>
{
doSomeWork();
}));
Dispatcher.Run();
});
serialQueueThread.Start();
Dispatcher.Run();
}
}
public static void doSomeWork() {
mainSerialQueue.BeingInvoke(...)
}
}
What I am doing here is basically getting the Dispatcher for the main thread, which I call mainSerialQueue and then create another thread, and get the Dispatcher for it, which I call backgroundSerialQeueue.
Whenever you need to invoke code on particlar thread - use SynchronizationContext of appropriate thread. For console app context is empty so you need to initialized it. 2 simple ways are:
Implement SynchorinzationContext with WPF dispatcher inside and set context for required thread by SynchronizationContext.SetSynchronizationContext
Create instance if System.Windows.Forms.Form class and SynchorinzationContext will be initialzed automitically on executing thread
Why not to use Dispatcher directly? If you'll find and problems with threading later, all you need is to fix SynchorinzationContext. At least you can switch between suggested approaches. Or you can write your own context, but doubt that it will be required.
One more thing - async, await are also build upon SynchorinzationContext.

Stop execution of any method without closing the application

I have an application which runs on a single thread, but does a lot of things (executing methods in a loop to automate webbrowser app).
I am a beginner, so the code is probably poorly organized, but I need to add a following feature to the program - a STOP button.
What it needs to do is simply send a 'return;' to any method that is or would be executed next, so that the program returns to a ready-and-waiting stage (i.e. I don't loose user provided data, but no other iteration of any loop is carried out etc.).
Any idea?
I tried System.Threading.Thread.CurrentThread.Abort(); but this actually kills the whole application. Any idea for a good generic solution?
Cheers!
Well first of all if you are just using one thread with your application. Then you cant send cancelTokens to your methods. However if you start using Tasks, which are threads then you can provide yourself the ability to use cancelTokens on your methods.
Here is a very simple example I wrote of using a cancelToken in a program that has threads.
class Program
{
static void Main(string[] args)
{
bool cancelToken = false;
Thread t = new Thread(new ThreadStart(() =>
{
while (!cancelToken)
{
Console.WriteLine("Running....");
Thread.Sleep(1000);
}
}));
t.Start();
Console.ReadKey();
cancelToken = true;
t.Join();
}
}
If you have a single-threaded GUI program, then you can't take any user commands while it's processing something. If you do as others have suggested, and dump the processing into a worker thread, then you can send an interrupt signal to that thread to stop it.

Microsoft snippet waiting for a System.Threading.Thread to complete

I was looking at the Microsoft MSDN reference page regarding the modifier "volatile", and was a little unsure as to the way in which the snippet they provided, waited for a thread to complete execution.
I know it is only example code, and that the thread completed very quickly, but I believe that the code below is not very good for developers trying to understand threading.
I believe Microsoft have actually presented a code snippet which will introduce a "tight-loop" in the code. Now I appreciate that it will not affect this code snippet (that much), but if a developer takes this code and tries to use it for some multi-threaded code that is a little more intensive, I would presume the "tight-loop" issue would arise?
using System;
using System.Threading;
class Test
{
public static int result;
public static volatile bool finished;
static void Thread2() {
result = 143;
finished = true;
}
static void Main() {
finished = false;
// Run Thread2() in a new thread
new Thread(new ThreadStart(Thread2)).Start();
// Wait for Thread2 to signal that it has a result by setting
// finished to true.
for (;;) {
if (finished) {
Console.WriteLine("result = {0}", result);
return;
}
}
}
}
Snippet reference:
http://msdn.microsoft.com/en-gb/library/aa645755(v=vs.71).aspx
What would be the better way to wait for the thread to finish, in the example above, which would not introduce this "tight-loop" situation?
Or, will a "tight-loop" not actually be introduced at all?
Please note, that the purpose of the snippet is to demonstrate the "volatile" keyword, so using a Thread.Join() would take the snippet out of context I believe.
This snippet doesn't illustrate how to wait, this just illustrates access to a volatile field from different threads.
To wait for your background thread simply, you can use this snippet:
AutoResetEvent autoEvent = new AutoResetEvent(false);
ThreadPool.QueueUserWorkItem((o) =>
{
// do your stuff
((AutoResetEvent)o).Set();
}, autoEvent);
autoEvent.WaitOne();
As you say the best way to wait for a thread to finish would be to use Thread.Join or an ManualResetEventSlim event however neither of these would require a volatile bool.
It would be possible to use the code in the example by adding a call to Thread.SpinWait in the loop. This would help to prevent processor starvation. In version 4 of .Net Microsoft added a struct called SpinWait that can be used more effectivly.
There is more information about this in "Threading in C#" by Joseph Albahari

fetch data from multiple database server at same time using multithreading c#

i want to call same database procedure from C# programe to multiple database server at same time.how we can implement using multithereading or any alternative method.
e.g. server1 takes 2 min,server2 takes 3 min,server3 takes 1 min
total time taken=6 min.
i want to run C# programe to run database procedure parallel to all server , so that i can get result within 2 min.
Sounds reasonable. You could create a method for each algorithm which performs the job you need. Then use ThreadPool to invoke this task in parallel.
if we have to use same function then i would have to implement multiple time? like this:
using System;
using System.Threading;
public class mythread
{
public static void Main()
{
// Queue the task.
Console.WriteLine(DateTime.Now);
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc1));
//ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc2));
Console.WriteLine("Main thread does some work, then sleeps.");
// If you comment out the Sleep, the main thread exits before
// the thread pool task runs. The thread pool uses background
// threads, which do not keep the application running. (This
// is a simple example of a race condition.)
Thread.Sleep(1000);
Console.WriteLine("Main thread exits.");
Console.WriteLine(DateTime.Now);
Console.Read();
}
// This thread procedure performs the task.
static void ThreadProc1(object obj)
{
// No state object was passed to QueueUserWorkItem, so
// stateInfo is null.
Console.WriteLine("Hello world!!,this is ONE.");
}
static void ThreadProc2(object obj)
{
// No state object was passed to QueueUserWorkItem, so
// stateInfo is null.
Console.WriteLine("Hello world!!,this is TWO.");
}
}

Windows Client GUI Design Advice - Accessing UI Thread from Long Running Task

Web Developer here and need some advice on how to achieve what must be a common requirement in Windows Forms.
I have a windows client app that calls a business object in a separate project to perform some long running tasks. Difference to other examples is that the process live in another class library i.e. Business.LongRunningTask();
I have a list box in the client that I would like to have logged to by the task. I can run the process on the UI thread passsing in the instance of the textbox and calling Application.DoEvents() when I log to the textbox from within the task. All fine, but not elegant and would prefer not to call Application.DoEvents();
If I run the long running process on a separate thread using delegates I cannot access the textbox or delegates created in the windows client form which rules out BeginInvoke calls.
Surely this is bad design on my part and would appreciate some feedback.
You're looking for the BackgroundWorker class.
To execute a time-consuming operation in the background, create a BackgroundWorker and listen for events that report the progress of your operation and signal when your operation is finished.
You can find a complete example here: http://msdn.microsoft.com/en-us/library/b2zk6580(v=VS.100).aspx#Y1351
I can run the process on the UI thread
passsing in the instance of the
textbox and calling
Application.DoEvents() when I log to
the textbox from within the task.
Yes, you could also pass in an instance of ILoggingINnterface that you have used to put in the code to write to the text box FROM WITHIN THE UI and thus have taken care of all the nice BginInvoke stuff ;)
If I run the long running process on a
separate thread using delegates I
cannot access the textbox or delegates
created in the windows client form
which rules out BeginInvoke calls.
Ah. No. You just most invoke back to the dispatcher thread then you can access all the UI elemente you like.
Yeah, avoid Application.DoEvents().
To marshall the call back onto the UI thread, call this.Invoke(YourDelegate)
To access UI elements from a different thread, you can use control.Invoke to call a delegate on the owning thread.
I used this at one point to create a live log screen which was updated from a timer while a different worker thread was running. Heres a simplified version:
public class DifferentClassLibrary
{
public delegate void StringDataDelegate(string data);
public event StringDataDelegate UpdatedData;
public void DoStuff()
{
if (UpdatedData != null)
{
Thread.Sleep(10000);
UpdatedData("data");
}
}
}
And in the winform:
public void UpdateTextBoxCallback(string data)
{
if (uiTextBoxLiveLogView.InvokeRequired)
{
uiTextBoxLiveLogView.Invoke(new DifferentClassLibrary.StringDataDelegate(UpdateTextBoxCallback), data);
}
else
{
uiTextBoxLiveLogView.Text += data;
}
}
void Main()
{
DifferentClassLibrary test = new DifferentClassLibrary();
test.UpdatedData += UpdateTextBoxCallback;
Thread thread = new Thread(new ThreadStart(test.DoStuff));
thread.Start();
}

Categories

Resources