How to get thread status..in Multi threading - c#

May be it sound dumb but if I want some computed value from other thread and other value from one more thread and this two value in my main thread how can I,if In case second thread completed before first one.it will create problem..so I just want is there any way that I can get the thread status means its still running or stop.
Thanks

Sounds like you want to wait until both threads have finished. Simply call Join on each of them. After the calls have returned, you know that both threads have finished.

Thread class have ThreadState property, but make sure you know about thread synchronization. Here are two articles:
http://msdn.microsoft.com/en-us/library/dsw9f9ts%28VS.71%29.aspx
http://msdn.microsoft.com/en-us/magazine/cc188793.aspx

Thread.ThreadState or Thread.Join if you want to wait for your threads. Or use Semaphore

Related

Thread Sleep by name or some any other method

is there anyway to sleep the some particularthread by name or some any other source
in case I've two threads
Thread call = new Thread(() => open_page(txtbx_1.Text));
call.Start();
Thread call_2nd = new Thread(() => open_page(txtbx_1.Text));
call_2nd.Start();
I want to sleep call and call_2nd for at least 15 minutes(but don't want to sleep the main Thread.
Thanks
No - you can't ask another thread to sleep. Apart from anything else, at the time when you want it to sleep it may hold a lock or other resource which really shouldn't be held while sleeping.
You'd have to do this cooperatively, with some sort of shared data between the threads indicating what you want to sleep and for how long. Alternatively, schedule a timer to only start the relevant activity after a certain length of time.
Why would you want a thread to sleep unless it was otherwise going to do something you didn't want it to do? And why would you ever code a thread to do something you didn't want to do?
If you're asking this question, something is very wrong somewhere in your design or implementation.
Yes, but in a different way than you might think.
Have the target thread(s) you want to sleep regularly check an manual-reset event. That event (flag) is cleared by the controlling thread whenever the target thread is supposed to sleep, otherwise it is always set. If you want the target thread(s) to sleep only for a certain amount of time, use that value as the wait timeout.
if the event is set (no sleep), the wait is satisfied immediately and execution continues
if the event is cleared (sleep), the target thread(s) stops until
the timeout (15 minutes = 15 * 60 * 1000 ms) elapsed
or the controlling thread sets the event again within that time frame
If you need to check whether or not the target thread(s) is in the waiting state, consider another event/flag/counter, set by the target thread(s), and read by the controlling thread.

Thread synchronization with EventHandler

I stuck with choosing synchronization primitive.
This is the case:
I have pool of threads, that are in infinitive loop, and waits for some event. And another thread that should invoke this event. When event fires all wating thread should make one iteration and fall back for waiting event again.
Should I use manualResetEvent for this? I can't understand, is there any garanty, that if i wrote in control thread something like this
event.Set();
event.Reset();
All waiting threads make iteration, and all waiting threads makes only one, not two ore three, iterations.
Or should I use another primitive for my case?
Use Monitor.Wait(someObject) in the looping threads, and Monitor.PulseAll(someObject) in the event raising thread.

C# Waiting and Disposing of Tasks

I have been looking at this article about using tasks in C#, and I was wandering if someone could clear something up for me? Doesn't calling wait on a task defeat the purpose of creating the task, because wouldn't it freeze up the main thread anyway because now the main thread has to wait for task to finish. I'm assuming however that wait won't be called straight away, so now when would you call it or how else would you know when to dispose of the task.
Assuming we have a simple case like this:
void MyFunction()
{
Task t = Task.Factory.StartNew(() => { System.Threading.Thread.Sleep(5000); });
}
if you call t.Wait() straight away the main thread will still wait 5 seconds before being able to do anything else, which kinda defeats the purpose from the users point of view, they wont be able to do anything for 5 seconds. How would you know that after 5 seconds that task has been completed? And you can dispose of t? What is a correct way of handling that? Sorry if the question is being really naive :(
Thanks All :D
You would probably never call Wait on a single task like this from a UI thread - as you said the whole point is not blocking the UI thread. In fact waiting on any task at all from the UI thread would be a problem.
Waiting for task completion might however be useful to synchronize multiple tasks and return a combined result - e.g. imagine two tasks that execute a hotel query on priceline and expedia concurrently and the thread that spawned both tasks (e.g. a background thread) waiting on the outcome of both and combining the results to order the available hotels on both sites by price.
The final result of the queries can then be dispatched back to the UI thread, typically by executing a callback or raising an event.

At what point is the Thread.CurrentThread evaluated?

In the following code:
ThreadStart ts = new ThreadStart((MethodInvoker)delegate
{
executingThreads.Add(Thread.CurrentThread);
// work done here.
executingThreads.Remove(Thread.CurrentThread);
});
Thread t = new Thread(ts);
t.Start();
Perhaps you can see that I'd like to keep track of the threads that I start, so I can abort them when necessary.
But I worry that the Thread.CurrentThread is evaluated from the thread that creates the Thread t, and thus aborting it would not abort the spawned thread.
Aborting threads is never a good idea. If you are 100% positive that whatever task you are performing in the thread you want to abort will not corrupt any state information anywhere else then you can probably get away with it, but its best to avoid doing so even in those cases. There are better solutions like flagging the thread to stop, giving it a chance to clean up whatever mess it may leave behind.
Anyhow, answering your question, Thread.CurrentThread is executing in the method invoked when the new thread starts executing, therefore it will return the new thread, not the thread where the new thread was created (if that makes sense).
In the code you have given, Thread.CurrentThread is called in the context of the thread t and not its creator.
Also, aborting threads is morally equivalent to killing puppies.
To answer your question, and without comment on the wisdom of aborting a thread (I agree with previous commenters by the way), Thread.CurrentThread, as you have written it, will do what you are expecting to do - it will represent the thread that is currently invoking your delegate, not the thread that created and started the thread.
First of all I think it's a bad idea to abort threads, check the other answers/comments for the reasons. But I'll leave that aside for now.
Since your calls are inside a delegate they'll only be evaluated once the thread executes the content of that delegate. So the code works as you expect it to work and you get the thread on which the delegate executes, not the thread which created the delegate.
Of course your code isn't exception safe, you should probably put the remove into a finally clause.
executingThreads must be a thread safe collection, or you need to use locking.
Another way to keep track of the threads is to add the created thread to a collection from the creating thread, and then use the properties of that thread to check if the thread has already terminated. That way you don't have to rely on the thread keeping track itself. But this still doesn't fix the abortion problem.

How to check if Thread finished execution

I have following problem:
I want to check (C#) if a thread has finished execution, i.e. if the thread method has returned. What I do now is call Thread.Join(1), but this gives a 1 ms delay. Is there any way to simply check if a thread has finished. Inspecting Thread.ThreadState just seems too cumbersome.
Use the Thread.IsAlive flag. This is to give the thread status.
For a thread you have the myThread.IsAlive property. It is false if the thread method returned or the thread was aborted.
If you don't want to block the current thread by waiting/checking for the other running thread completion, you can
implement callback method like this.
Action onCompleted = () =>
{
//On complete action
};
var thread = new Thread(
() =>
{
try
{
// Do your work
}
finally
{
onCompleted();
}
});
thread.Start();
If you are dealing with controls that doesn't support cross-thread operation, then you have to invoke the callback method
this.Invoke(onCompleted);
You could fire an event from your thread when it finishes and subscribe to that.
Alternatively you can call Thread.Join() without any arguments:
Blocks the calling thread until a thread terminates, while continuing to perform standard COM and SendMessage pumping.
Thread.Join(1) will:
Blocks the calling thread until a thread terminates or the specified time elapses, while continuing to perform standard COM and SendMessage pumping.
In this case the specified time is 1 millisecond.
Use Thread.Join(TimeSpan.Zero) It will not block the caller and returns a value indicating whether the thread has completed its work. By the way, that is the standard way of testing all WaitHandle classes as well.
I use IsAlive extensively, unless I want to block the current execution (of the calling thread), in which case I just call Join() without a parameter. Now, be aware that IsAlive may return false if the target thread has not actually started execution yet for any reason.
Carlos Merighe.
It depends on how you want to use it. Using a Join is one way. Another way of doing it is let the thread notify the caller of the thread by using an event. For instance when you have your graphical user interface (GUI) thread that calls a process which runs for a while and needs to update the GUI when it finishes, you can use the event to do this. This website gives you an idea about how to work with events:
http://msdn.microsoft.com/en-us/library/aa645739%28VS.71%29.aspx
Remember that it will result in cross-threading operations and in case you want to update the GUI from another thread, you will have to use the Invoke method of the control which you want to update.
Take a look at BackgroundWorker Class, with the OnRunWorkerCompleted you can do it.

Categories