At what point is the Thread.CurrentThread evaluated? - c#

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.

Related

Make Task.Delay continue on the calling thread

Consider this method:
//Called on a known thread
public async void ThreadSleep()
{
while(itemsInQueue)
{
//This call is currently on Thread X
await Task.Delay(5000);
//This needs to be on the thread that the method was called on
DoSomeProcessing();
}
}
I am assuming that the Task.Delay is executing async on a different thread and resumes on that same thread. This was not very obvious to me. How do I get the method to continue on Thread X?
PS: The ThreadSleep method executes on a non UI thread
Edit: 1) Added W.Brian's code example for simplicity.
2) Yes, this example is exactly that... an example.
3) The purpose of Thread.Delay is just to add some delay between processing.
You need to create your own synchronization context (like the UI thread does).
There's a pretty good article on MSDN that helps to understand the problem and how to create a solution.
Mind if I ask why you have to continue on the same thread?
Usually it shouldn't create and issues when a new thread is used since the context is preserved.
If you need to preserve some kind of context between calls at a deeper level (like you would do with ThreadLocal), I suggest you use the new AsyncLocal to achieve this goal.
It makes sure that immutable objects stay within the async context even if the thread is changed (refer to: How do the semantics of AsyncLocal differ from the logical call context?).
await Task.Delay(5000).ConfigureAwait(true);
Calling ConfigureAwait(true) should work as it ensures the same context as the original thread even if the thread changes. This assumes that ThreadLocal<T> is not being used, in which case async/await will generally cause problems and Thread.Sleep may be preferred if you can't change the rest of the code.

Can ProgressBar cause the application to go into racing condition?

Description (.Net framework 3.5/Windows7/VS12) :
1) Operation is a type that can be run asynchronously. It notifies other objects through it's event named Executed , as follows :
_Operation.Executed += OperationExecuted;
2) Inside this event, we call the StopProgress() as follows :
private void OperationExecuted (object sender, OperationEventArgs e)
{
StopProgress();
}
3) The StopProgress() is as shown below :
public void StopProgress()
{
if (InvokeRequired)
{
Invoke(new MethodInvoker(StopProgress));
return;
}
lblTemp.Text = "operation complete. ";// 1
//progressBar1.Visible = false; // 2
// with added locks the app totally hangs
//lock (progressBar1)
//{
// progressBar1.Visible = false;
//}
}
When commenting line marked "1" (inside StopProgress() ), and uncommenting "2" (which is the desired behavior), we run into racing condition occasionally(after running the app for 5-10 times, we encounter racing conditions). With line "1", it never happens. There is no exceptions thrown(caught/uncaught) either. We are assuming the problem is related to the "ProgressBar" itself. If not, what could probably be the case here . Any suggestions on how to track down the racing conditions (vulnerable code sections) are also very much appreciated.
Thanks.
Hard to explain this one, but there are some strong anti-patterns in this code that can induce deadlock.
First off, you are using Control.Invoke() to ensure that the progress bar update occurs on the UI thread. It is therefore completely unnecessary to use the lock statement since you are already know that updates only ever happen on one thread. So remove the lock.
Using Control.Invoke() is a bad anti-pattern. It is particularly prone to cause deadlock since it cannot complete until the UI thread has executed the delegate target. Deadlock will occur when there's other code somewhere that runs on the UI thread that waits for the thread to complete. That will never happen, the thread is stuck in the Invoke() call which can't complete until the UI thread goes idle. The UI thread cannot get idle, it is stuck waiting for the thread to complete. Deadlock city. Use Invoke() only when absolutely necessary and fear its ability to cause deadlock. Always favor BeginInvoke() instead, it cannot cause deadlock since it doesn't wait. And you don't need Invoke() here, you don't need to know its return value.
Using Control.InvokeRequired is an anti-pattern as well. You almost always know that a method is called from a worker thread. So no point in testing InvokeRequired, you expect it to be true. Very Bad Things happen when it is false. Which is very possible, it will happen when the user closes the form and the worker thread is allowed to continue executing. This will normally cause your code to crash with a ObjectDisposedException. But your code doesn't get there, it is liable to deadlock before that happens, either on the Invoke call or the lock. You should use InvokeRequired, but throw an InvalidOperationException when it is false. Now you added a diagnostic that gives you a chance to find out what is going wrong.
Get ahead by using a .NET class that already takes care of these things. BackgroundWorker does everything you are trying to do by hand. You will now also have a shot at dealing with the problem of the user closing the form with the worker thread still executing. The subject of this answer.
To avoid this, most probabbly, you can put the code
progressBar1.Visible = false
just inside StopProgress(..) method.
The point here, imo, is that in case of InvokeRequired, the StopProgress(..) will be called and contemporary (it's multithreading) you may run the code progressBar1.Visible = false;. This may produce undesirable results.
So to avoid this "destribution", move progressBar1.Visible = false; into method itself, if this is possible.
Hope this helps.

Is using Thread.Abort() and handling ThreadAbortException in .NET safe practice?

I need to develop a multithreaded Azure worker role in C# - create multiple threads, feed requests to them, each request might require some very long time to process (not my code - I'll call a COM object to do actual work).
Upon role shutdown I need to gracefully stop processing. How do I do that? Looks like if I just call Thread.Abort() the ThreadAbortException is thrown in the thread and the thread can even use try-catch-finally (or using) to clean up resources. This looks quite reliable.
What bothers me is that my experience is mostly C++ and it's impossible to gracefully abort a thread in an unmanaged application - it will just stop without any further processing and this might leave data in inconsistent state. So I'm kind of paranoid about whether anything like that happens in case I call Thread.Abort() for a busy thread.
Is it safe practice to use Thread.Abort() together with handling ThreadAbortException? What should I be aware of if I do that?
Is using Thread.Abort() and handling ThreadAbortException in .NET safe practice?
TL;DR version: No, isn't.
Generally you're safe when all type invariants (whether explicitly stated or not) are actually true. However many methods will break these invariants while running, only to reach a new state when they are again true at the end. If the thread is idle in a state with invariants held you'll be OK, but in that case better to use something like an event to signal the thread to exit gracefully (ie. you don't need to abort).
An out-of-band exception1 thrown in a thread while in such a invariants-not-true, ie. invalid, state is where the problems start. These problems include, but are certainly not limited to, mutually inconsistent field and property values (data structures in an invalid state), locks not exited, and events representing "changes happened" not fired.
In many cases it is possible to deal with these in clean up code (eg. a finally block), but then consider what happens when the out-of-band exception occurs in that clean up code? This leads to clean up code for the clean up code. But then that code is it self vulnerable so you need clean up code for the clean up code of the clean up code… it never ends!
There are solutions, but they are not easy to design (and tends to impact your whole design), and even harder to test—how to re-create all the cases (think combinatorial explosion). Two possible routes are:
Work on copies of state, update the copies and then atomically swap current for new state. If there is an out-of-band exception then the original state remains (and finalisers can clean up the temporary state).
This is rather like the function of database transactions (albeit RDBMSs work with locks and transaction log files).
It is also similar to the approaches to achieving the "strong exception guarantee" developed in the C++ community in response to a paper questioning if exceptions could ever be safe (C++ of course has no GC/finaliser queue to clean up discarded objects). See Herb Sutters "Guru of the Week #8: CHALLENGE EDITION: Exception Safety" for the solution.
In practice this is hard to achieve unless your state can be encapsulated in a single reference.
Look at "Constrained Execution Regions", but not the limitations on what you can do in these cases. (MSDN Magazine had an introductory article (introduction to the subject, not introductory level), from .NET 2 beta period2).
In practice if you have to do this, using approach #2 to manage the state change under #1 is probably the best approach, but getting it right, and then validating that it is correct (and the correctness is maintained) is hard.
Summary: It's a bit like optimisation: rule 1: don't do it; rule 2 (experts only): don't do it unless you have no other option.
1 A ThreadAbortException is not the only such exception.
2 So details have possibly changed.
One example where it's problematic to abort a thread.
using(var disposable=new ClassThatShouldBeDisposed())
{
...
}
Now the Thread abortion happes after the constructor of the class has finished but before the assignment to the local variable. So it won't be disposed. Eventually the finalizer will run, but that can be much later.
Deterministic disposing and thread abortion don't work well together. The only way I know to get safe disposing when using thread abortion is putting all the critical code inside a finally clause.
try
{//Empty try block
}
finally
{
//put all your code in the finally clause to fool thread abortion
using(var disposable=new ClassThatShouldBeDisposed())
{
...
}
}
This works because thread abortion allows finally code to execute. Of course this implies that the thread abortion will simply not work until the code leaves the finally block.
One way to get your code to work correctly with thread abortion is using the following instead of the using statement. Unfortunately it's very ugly.
ClassThatShouldBeDisposed disposable=null;
try
{
try{}finally{disposable=new ClassThatShouldBeDisposed();}
//Do your work here
}
finally
{
if(disposable!=null)
disposable.Dispose();
}
Personally I just assume threads never get aborted(except when unloading the AppDomain) and thus write normal using based code.
It's very difficult to handle the TheadAbortException correctly, because it can be thrown in the middle of whatever code the thread is executing.
Most code is written with the assumption that some actions, for example int i = 0; never causes an exception, so the critical exception handling is only applied to code that actually can cause an exception by itself. When you abort a thread, the exception can come in code that is not prepared to handle it.
The best practice is to tell the thread to end by itself. Create a class for the method that is running the thread, and put a boolean variable in it. Both the code that started the thread and the method running the thread can access the variable, so you can just switch it to tell the thread to end. The code in the thread of course have to check the value periodically.
Thread.Abort is an unsafe way of killing the thread.
It rises an asynchronous ThreadAbortException which is a special exception that can be caught, but it will automatically be raised again at the end of the catch block
It can leave the state corrupted, and your application becomes unstable
TAE is raised in the other thread
The best practise is to use wrappers that support work cancellation, such as the Task class or use volatile bool. Instead of Thread.Abort consider using Thread.Join which will block the calling thread until the working thread is disposed of.
Some links:
- How To Stop a Thread in .NET (and Why Thread.Abort is Evil)
- Managed code and asynchronous exception hardening
- The dangers of Thread.Abort
As others have mentioned, aborting a thread is probably not a good idea. However, signalling a thread to stop with a bool may not work either, because we have no guarantee that the value of a bool will be synchronized across threads.
It may be better to use an event:
class ThreadManager
{
private Thread thread = new Thread(new ThreadStart(CallCOMMethod));
private AutoResetEvent endThread = new AutoResetEvent(false);
public ThreadManager()
{
thread.Start();
}
public StopThread()
{
endThread.Set();
}
private void CallCOMMethod()
{
while (!endThread.WaitOne())
{
// Call COM method
}
}
}
Since the COM method is long running you may just need to "bite the bullet" and wait for it to complete its current iteration. Is the information computed during the current iteration of value to the user?
If not, one option my be:
Have the ThreadManager itself run on a separate thread from the UI which checks for the stop notification from the user relatively often.
When the user requests that the long running operation be stopped, the UI thread can immediately return to the user.
The ThreadManager waits for the long running COM operation to complete its current iteration, then it throws away the results.
It's considered best practice to just let the thread's method return:
void Run() // thread entry function
{
while(true)
{
if(somecondition) // check for a terminating condition - usually "have I been disposed?"
break;
if(workExists)
doWork();
Thread.Sleep(interval);
}
}
Please get simple idea from here as for your requirement, check thead isalive property, then abort your thread.............................................................
ThreadStart th = new ThreadStart(CheckValue);
System.Threading.Thread th1 = new Thread(th);
if(taskStatusComleted)
{
if (th1.IsAlive)
{
th1.Abort();
}
}
private void CheckValue()
{
//my method....
}

Busy waiting in C#

How do you implement busy waiting in a not total inefficient way? I am facing the issue that I can load the data of my model only in a pull manner, which means I have to invoke getXYZ() methods in a continuous way.
This has to happen not fast enough for user interaction, but fast enought, that when a state in the GUI is changed, the model can be noticed and the new state is received by the getXYZ() methods.
My approach simply be:
while (c.hasChanged()) {
Thread.sleep(500);
}
updateData();
Are there better mechanisms?
Your problem seems to be solvable with Threading.
In WPF you can do:
Thread t = new Thread((ThreadStart)delegate() {
while (true) {
Thread.sleep(500);
if (c.hasChanged())
Dispatcher.Invoke((Action)delegate() {updateData();});
}
}).Start();
In WinForms
Thread t = new Thread((ThreadStart)delegate() {
while (true) {
Thread.sleep(500);
// this must derive from Control
if (c.hasChanged())
this.Invoke((Action)delegate() {updateData();});
}
}).Start();
There may be missing parameters to Invoke (which is needed to execute the code on the calling UI thread) but I'm writing this from my brain so no intellisense at disposal :D
In .NET 4 you can use TaskFactory.StartNew instead of spawning a thread by yourself.
In .Net <= 4, you could use the TreadPool for the thread.
However I recall you need this to be run at once because you expect it to be there checking as soon as possible and the thread pool won't assure you that (it could be already full, but not very likely:-).
Just don't do silly things like spawning more of them in a loop!
And inside the thread you should put a check like
while (!Closing)
so that the thread can finish when you need it without having to resort to bad things like t.Abort();
An when exiting put the Closing to true and do a t.Join() to close the checker thread.
EDIT:
I forgot to say that the Closing should be a bool property or a VOLATILE boolean, not a simple boolean, because you won't be ensured that the thread could ever finish (well it would in case you are closing the application, but it is good practice to make them finish by your will). the volatile keyword is intended to prevent the (pseudo)compiler from applying any optimizations on the code that assume values of variables cannot change
It's not clear from your post exactly what you are trying to do, but it sounds like you should put your model/service calls on a separate thread (via Background worker or async delegate) and use a callback from the model/service call to notify the UI when it's done. Your UI thread can then do busy things, like show a progress bar, but not become unresponsive.
If you are polling from a GUI, use a (WinForms) Timer.
If this is some kind of background process, your Sleep() may be the lesser evil.
Explicit busy waiting is evil and must be avoided whenever possible.
If you cannot avoid it, then build your application using the Observer design pattern and register the interested objects to an object which performs the polling, backed by a thread.
That way you have a clean design, confining the ugly stuff in just one place.

Control.Invoke vs Tasks with a TaskScheduler

I've looked all over and I can't find an answer.
Is it better, worse, or indifferent to use:
{
...
RefreshPaintDelegate PaintDelegate = new RefreshPaintDelegate(RefreshPaint);
Control.Invoke(PaintDelegate);
}
protected void RefreshPaint()
{
this.Refresh();
}
...or...
Task.Factory.StartNew(() =>
{
this.Refresh();
},
CancellationToken.None,
TaskCreationOptions.None,
uiScheduler);
Assuming that uiScheduler is a scheduler that will delegate the calls to the UI thread, I would say that functionally, using the two is indifferent (with the exception that the call to Control.Invoke will block until the call completes, whereas the call to Task will not, however, you can always use Control.BeginInvoke to make them semantically equivalent).
From a semantic point of view, I'd say that using Control.Invoke(PaintDelegate) is a much better approach; when using a Task you are making an implicit declaration that you want to perform a unit of work, and typically, that unit of work has the context of being scheduled along with other units of work, it's the scheduler that determines how that work is delegated (typically, it's multi-threaded, but in this case, it's marshaled to the UI thread). It should also be said that there is no clear link between the uiScheduler and the Control which is linked to the UI thread that the call should be made one (typically, they are all the same, but it's possible to have multiple UI threads, although very rare).
However, in using Control.Invoke, the intention of what you want to do is clear, you want to marshal the call to the UI thread that the Control is pumping messages on, and this call indicates that perfectly.
I think the best option, however, is to use a SynchronizationContext instance; it abstracts out the fact that you need to synchronize calls to that context, as opposed to the other two options, which are either ambiguous about the intent in the call (Task) or very specific in the way it is being done (Control.Invoke).
It is not same. First version will block the calling thread until UI thread is ready to invoke the method. For a non blocking version, you should use Control.BeginInvoke, which also returns immediately.
Apart from that (if you are comparing Task to a Thread Pool thread), there is little difference in using them.
[Edit]
In this case, there is no difference between Task.Factory.StartNew and Control.BeginInvoke (but not Invoke as I wrote above), since there is only a single GUI thread which can execute your code. No matter how many calls you make using either of them, they will still execute sequentially when UI thread becomes free.

Categories