How would I go about in creating a thread in C#?
In java I would either implement the Runnable interface
class MyThread implements Runnable{
public void run(){
//metthod
}
and then
MyThread mt = new MyThread;
Thread tt = new Thread(mt);
tt.start()
or I could simply extend the Thread class
class MyThread extends Thread{
public void run(){
//method body
}
and then
MyThread mt = new MyThread
mt.start();
No, contrary to Java, in .NET you can't extend the Thread class because it's sealed.
So to execute a function in a new thread the most naive way is to manually spawn a new thread and pass it the function to be executed (as anonymous function in this case):
Thread thread = new Thread(() =>
{
// put the code here that you want to be executed in a new thread
});
thread.Start();
or if you don't want to use an anonymous delegate then define a method:
public void SomeMethod()
{
// put the code here that you want to be executed in a new thread
}
and then within the same class start a new thread passing the reference to this method:
Thread thread = new Thread(SomeMethod);
thread.Start();
and if you want to pass parameters to the method:
public void SomeMethod(object someParameter)
{
// put the code here that you want to be executed in a new thread
}
and then:
Thread thread = new Thread(SomeMethod);
thread.Start("this is some value");
That's the native way to execute tasks in background threads. To avoid paying the high price of creating new threads you could use one of the threads from the ThreadPool:
ThreadPool.QueueUserWorkItem(() =>
{
// put the code here that you want to be executed in a new thread
});
or using an asynchronous delegate execution:
Action someMethod = () =>
{
// put the code here that you want to be executed in a new thread
};
someMethod.BeginInvoke(ar =>
{
((Action)ar.AsyncState).EndInvoke(ar);
}, someMethod);
And yet another, and more modern way to execute such tasks is to use the TPL (starting from .NET 4.0):
Task.Factory.StartNew(() =>
{
// put the code here that you want to be executed in a new thread
});
So, yeah, as you can see, there are like gazzilions of techniques that could be used to run a bunch of code on a separate thread.
Related
I have windows project and one form which have timer for each 5 seconds.
It calls and processes methods from request named table time wise and condition wise.
But I have some methods types which takes too much time to respond and want those methods in separate thread. So that I can run those both request types in separate threads and syncs.
How can I do separate those both using thread -- multi async threads?
I recommend you look at the .NET 4.0 Task class. Firing full threads every time might be overkill. Tasks, together with timers use the underlying thread pool to execute work in parallel.
Using a Task is as simple as:
Task t = Task.Factory.StartNew(
() =>
{
// task code here
});
using System;
using System.Threading;
class Program
{
static void Main()
{
Thread thread1 = new Thread(new ThreadStart(A));
Thread thread2 = new Thread(new ThreadStart(B));
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
}
static void A()
{
Thread.Sleep(100);
Console.WriteLine('A');
}
static void B()
{
Thread.Sleep(1000);
Console.WriteLine('B');
}
}
Threading Tutorial
There is a method that is called continuously in my program and so I want to thread it such that the GUI doesn't freeze whilst it goes about its business.
Thread t = new Thread(Class2.ArrayWorkings(1, MyGlobals.variable1));
t.start();
int[] localVariable1 = ??// I want to move the value returned from the method into localVariable1.
Currently my errors are:
The best overloaded method match for 'System.Threading.Thread.Thread(System.Threading.ParameterizedThreadStart)' has some invalid arguments
&
Argument 1: cannot convert from 'method group' to 'System.Threading.ParameterizedThreadStart'
Currently doing this without threading like:
int[] localVariabl1 = Class2.ArrayWorkings(1, MyGlobals.variable1);
You can fix the constructor by using a lambda:
Thread t = new Thread(() => Class2.ArrayWorkings(1, MyGlobals.variable1));
but that doesn't let you (as Jon notes) get the result straight away - otherwise you are writing synchronous code again. You can instead look to some kind of callback; presumably you need to get back to the UI thread, so:
Thread t = new Thread(() => {
// this runs on the worker
int[] localVariabl1 = Class2.ArrayWorkings(1, MyGlobals.variable1);
this.Invoke((MethodInvoker)delegate {
// now we're back on the UI thread!
update the UI from localVariabl1
});
});
t.Start()
I would probably suggest using the thread-pool, though:
ThreadPool.QueueUserWorkItem(delegate {
// this runs on the worker
int[] localVariabl1 = Class2.ArrayWorkings(1, MyGlobals.variable1);
this.Invoke((MethodInvoker)delegate {
// now we're back on the UI thread!
update the UI from localVariabl1
});
});
You gotto put a ThreadStart Delegate. If you really dont want UI to get affected, u should use BackgroundWorker Class.
One way of doing it is as following:
ThreadStart starter = delegate { Class2.ArrayWorkings(1, MyGlobals.variable1); };
var thread = new Thread(starter);
thread.Start();
Edit: Just saw that you also want to capture the return value from the thread.
You may have to use ThreadPool.QueueUserWorkItem as mentioned in Marc's answer
Something you might want to look at is .NET Framework 4.5 (still in Release Candidate)
Makes life easier with Asynchronous programming.
await operator in .NET 4.5
Tasks provide an easy interface for performing an asynchronous job that will eventually return a value. A Task<string> for example is a task that (eventually) returns a string where a Task<int[]> will return an array of integers.
int[] localVariable1;
// start the task
Task<int[]> myTask = Task.Factory.StartNew<int[]>(() => Class2.ArrayWorkings(1, MyGlobals.Variable1);
// when it is finished get the result and place in local variable
myTask.OnCompleted(task => localVariable1 = task.Result;);
If you want to update a UI compontent once the asynchronous operation is finished, you will have to use Invoke (for winforms). This allows you to work with objects that live on the UI thread (such as buttons and labels).
myTask.OnCompleted(task => localVariable1.Invoke(new Action(() =>
localVariable1.Value = task.Result; )));
I'm trying to implement an algorithm that should run in parallel using threads or tasks. The difficulty is that I want the threads/tasks to share their best results from time to time with all other threads.
The basic idea is this:
//Accessible from each thread
IProducerConsumerCollection<MyObject> _bestObjects;
//Executed in each thread
DoSomeWork(int n){
MyObject localObject;
for(var i = 0; i < n; i++){
//Do some calculations and store results in localObject
if((i/n)%0.5 == 0)
{
//store localObject in _bestObjects
//wait until each thread has stored its result in _bestObjects
//get the best result from _bestObjects and go on
}
}
}
How can this be achieved using System.Threading or System.Threading.Tasks and is it true that tasks should not be used for long running operations?
Update: Clarification
It's not my problem to have a thread safe collection but to make the threads stop, publish result, wait until all other threads have publihed their results to and then go on again. All threads will run simultaneously.
Cutting a long story short:
Whats better for long running operations? Task or Thread or anything else?
How to communicate between threads/taks to inform each of them about the state of all other assuming that the number of threads is set at runtime (depending on available cores).
Best Regards
Jay
Look at the dollowing example.
public class Worker
{
public SharedData state;
public void Work(SharedData someData)
{
this.state = someData;
while (true) ;
}
}
public class SharedData {
X myX;
public getX() { ... }
public setX(anX) { ... }
}
public class Sharing
{
public static void Main()
{
SharedData data = new SharedDate()
Worker work1 = new Worker(data);
Worker work2 = new Worker(data);
Thread thread = new Thread(new ThreadStart(work1.Work));
thread.start();
Thread thread2 = new Thread(new ThreadStart(work2.Work));
thread2.start();
}
}
bomslang's response is not accurate. Cannot instantiate a new thread with ThreadStart, passing in Work method which requires a parameter to be passed in the above example. ParameterizedThreadStart would be more suitable. The sample code for the Main method would look more like this:
public class Sharing
{
public static void Main()
{
SharedData data = new SharedDate()
Worker work1 = new Worker(data);
Worker work2 = new Worker(data);
Thread thread = new Thread(new ParameterizedThreadStart(work1.Work));
thread.start(someData);
Thread thread2 = new Thread(new ParameterizedThreadStart(work2.Work));
thread2.start(someData);
}
}
Note that 'work' is being passed into the ParameterizedThreadStart as the method for the new thread to execute, and the data required to pass in to the 'work' method is being passed in the call to start. The data must be passed as an object, so the work method will need to cast it back to the appropriate datatype as well. Lastly, there is also another approach to passing in data to a new thread via the use of anonymous methods.
What do i create at thread with a function with parameters?
Thread t = new Thread(new ParameterizedThreadStart(fetchQuotes(cp)));
void fetchQuotes(SomeObject obj)
{
[DoSomething With SomeObject]
}
The easiest approach here is to use a closure over the non-parameterised (ThreadStart) signature:
Thread t = new Thread(() => fetchQuotes(cp));
...
t.Start();
This is static-checked for correctness at compile-time, and convenient (you can pass any number of parameters, for example).
The other approach is to pass object as the parameter (ParameterizedThreadStart):
Thread t = new Thread(fetchQuotes);
...
t.Start(cp);
...
void fetchQuotes(object obj)
{
SomeObject obj2 = (SomeObject) obj;
[DoSomething With SomeObject]
}
here we are passing object, so not type-checked at compile time. "braindead" errors will only surface at runtime.
I'll add the TPL syntax here for completeness (see my previous comment).
Task task = new Task(() => FetchQuotes(arg));
task.Start();
The task library has plenty of options for running on the calling thread, or async on one or many threads etc.
http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx
how threads communicate with eachother? they dont use values of eachother, then what is the way of communication between them?
There are a few ways threads can communicate with each other. This list is not exhaustive, but does include the most used strategies.
Shared memory, like a variable or some other data structure
Synchronization primitives, like locks and sempahores
Events, like ManualResetEvent or AutoResetEvent
Shared memory
public static void Main()
{
string text = "Hello World";
var thread = new Thread(
() =>
{
Console.WriteLine(text); // variable read by worker thread
});
thread.Start();
Console.WriteLine(text); // variable read by main thread
}
Synchronization primitives
public static void Main()
{
var lockObj = new Object();
int x = 0;
var thread = new Thread(
() =>
{
while (true)
{
lock (lockObj) // blocks until main thread releases the lock
{
x++;
}
}
});
thread.Start();
while (true)
{
lock (lockObj) // blocks until worker thread releases the lock
{
x++;
Console.WriteLine(x);
}
}
}
Events
public static void Main()
{
var are = new AutoResetEvent(false);
var thread = new Thread(
() =>
{
while (true)
{
Thread.Sleep(1000);
are.Set(); // worker thread signals the event
}
});
thread.Start();
while (are.WaitOne()) // main thread waits for the event to be signaled
{
Console.WriteLine(DateTime.Now);
}
}
"they don't use values of each other" - well two threads in the same process can see common variables, so that's the simples appraoch. So we use various synchronization, locking, mutices and sempahores to wait for conditions and wake up waiting threads.
In Java you use various primitives such as synchronization. You could read this tutorial
Threads can share values, they just have to be careful when doing so. In .Net the most common methods are the lock statement and the Interlocked class.