How to kill a thread in asp.net core - c#

I am writing an application using asp.net core in which I need to create a new thread as I have an always running loop. At some point, I need to mill this thread. In asp.net, Thread.abort was the solution, but it is removed in asp.net core. What is the alternative solution for this?

Do not create your own thread for something like this!
There is a built-in method for using long running tasks in asp.core. You should read about this here.
You should create a class which derives from BackgroundService. Using this class is the easiest way to create a background-service that implements IHostedService. You can then add this to your program by calling services.AddHostedService<YourBackgroundService>() in the ConfigureServices method.
Note: In the page I linked, they use AddSingleton instead of AddHostedService. In .net core 2.1 and above you should use AddHostedService, not AddSingleton (there are some exceptions but we're talking in general here). See this answer for why that is.
If you implement your background-service like this, the shutdown of the additional thread will be handled for you. In your implementation of ExecuteAsync you need to just check if you should stop executing with the provided CancellationToken. You should also use asnyc implementations where possible and provide the CancellationToken there as well so the thread can end gracefully. You will never need to call Thread.Abort or even have access to the Thread itself; it's all done in the background for you.
Since this is not a direct answer to the question you asked but more of a correction of what you're probably doing wrong to get into this situation in the first place, I first wanted to make this a comment. However it's just too long and there are too many things to mention that's why I made this into an answer.
Hope this helps.

The cleanest way to do this via a flag that is set by the "killing" thread and checked periodically by the thread that needs to be killed. Thread.Abort() is not a reliable way to do it; even the MSDN says Calling this method usually terminates the thread.

Related

Do I use a JoinableTaskFactory with AspNetCore?

I've imported Microsoft.VisualStudio.Threading into .Net Core Web App. I did this specifically to make use of AsyncLazy<T>.
I wanted to make sure I did this right, so I imported the appropriate Analyzers.
The warnings and the documentation clearly state that a JoinableTaskFactory should be injected into my implementation.
My question is, how should I instantiate that JoinableTaskFactory in the configuration of my .Net Core Web App?
Is it as simple as
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddSingleton(new JoinableTaskFactory());
// ...
}
or, is that all wrong?
Yes, you can use the Microsoft.VisualStudio.Threading library in ASP.NET Core applications. But while JoinableTaskFactory would "work" in such an app, it's a pretty good sign you're doing something wrong.
The analyzers are always appropriate of course, and the warnings you saw were perhaps pointing out that you shouldn't call Task.Result, Task.Wait(), etc. These synchronously block threads and can severely reduce the scalability of your web app (or any app for that matter). You should use await instead wherever possible.
JoinableTaskFactory is there to step in when you can't use await but you still need to call async code. Using JTF.Run will still block the calling thread, but it will do so in a way that avoids deadlocks when you have a single threaded SynchronizationContext in the application. I don't think ASP.NET Core has such a thing, so that's not a concern. JTF.Run is still more efficient than Task.Wait since it can reuse the original thread for continuations instead of a second thread.
If you do choose to use JTF in your web app, if ASP.NET Core doesn't use a single-threaded SynchronizationContext then you can create and share a single JTF instance with the entire app. But if it does have a single-threaded SynchronizationContext, it will be one per web request, which means you need to create a new JoinableTaskContext for each request since these are affinitized to one SynchronizationContext. You always get your JTF instance from a JoinableTaskContext instance.
This page of the vs-threading docs says
The ThreadHelper.JoinableTaskFactory property only works for code running in the VS process. If your code is running out of proc (in the vstest.executionengine.exe runner for instance) it won't work.
So, as the name of the package, Microsoft.VisualStudio.Threading, suggests, it's intended to be used for Visual Studio extensions. The code that you linked for its implementation of AsyncLazy uses JoinableTaskFactory, so it's probably not suitable outside of Visual Studio. I certainly would never use it outside of a VS extension that needs to switch to the UI thread.
Steven Cleary's AsyncEx library has an AsyncLazy, and the wiki page links to this Steven Toub blog post titled AsyncLazy. The blog post points out that the lazy semantics doesn't really add much over what Task<T> provides, although since the value factory might do a lot of work before reaching an await his sample runs it on the thread pool and unwraps the Task<Task<T>>.
edit: As pointed out in the comments, my quote from the docs is somewhat out of context. However, the vs-threading library is about avoiding deadlocks when using async with a synchronisation context (primarily a GUI). ASP.NET Core, what the author of the question is using, does not have a synchronisation context, hence doesn't need to worry about deadlocking the main thread specifically. While using the vs-threading library probably won't cause problems, as my quote claimed, I still don't think it's a good fit for anything without a synchronisation context and there are much better alternatives, like using Task<T> directly and not need any AsyncLazy implementation.

Is there any drawback of using ThreadPool.QueueUserWorkItem in web app.

I did some research on this topic, but I am unable to find the expected answer for this. In my application I have used
ThreadPool.QueueUserWorkItem
Like following way.
ThreadPool.QueueUserWorkItem(o => CaseBll.SendEmailNotificationForCaseUpdate(currentCase, caseUpdate));
My app in asp.net mvc & I have handled all background task which is not required to execute on user operation for faster execution & quick user response.
Now I wants to know that, Is there any bad side of using ThreadPool.QueueUserWorkItem When we have larger audience for application.
No, you should never use it. I can write a lot of reasons why but instead you should read this article from Scott Hansleman who is a genius IMHO
http://www.hanselman.com/blog/ChecklistWhatNOTToDoInASPNET.aspx
Under "Reliability and Performance":
Fire-and-Forget Work - Avoid using ThreadPool.QueueUserWorkItem as your app pool could disappear at any time. Move this work outside or use WebBackgrounder if you must.
So, as recommended, don't use ThreadPool.QueueUserWorkItem. An excellent alternative for this is at:
https://www.asp.net/aspnet/overview/web-development-best-practices/what-not-to-do-in-aspnet-and-what-to-do-instead#fire
Edit: As mentioned by #Scott-Chamberlain, here's a better link:
http://www.hanselman.com/blog/HowToRunBackgroundTasksInASPNET.aspx
It really depends on what you are going to be doing but generally speaking, your likely concerns will be:
Persistence. Threads in the managed pool are background threads. They will die when the application recycles which is generally undesirable. In your case you want to send e-mails. Imagine if your process dies for some reason before the thread executes. Your e-mail will never be sent.
Local storage is shared, which means you need to make sure there are no leftovers from the last thread if using it. Applies to fields marked with ThreadStaticAttribute as well.
I would instead recommend that you implement a job scheme where you schedule the job somewhere and have some other component actually read from this list (e.g. database) and perform the job, then mark it as complete. That way it persists across application unload, there is no memory reuse and you can throttle the performance. You could implement the processing component inside your application or even as a Windows service if you prefer.

Threading fiasco problem C#

I'm working on integrating a single-threaded API that does not have any multi-threaded support into a multi-threaded program. I would like to keep all APIinteraction on the main thread and do other stuff on other threads. However the program I am working with has a Producer-Consumer oriented threading design(which I can't modify).
Is there a way I can make threads switch to main thread when I want? Or some other way to get it working?
I apologize for not being able to express the problem clearer
You can use Control.Invoke on a worker thread to have it run some code on the main user interface thread.
Or maybe you could just synchronize all access to the single-threaded API using lock?
More details would be great, but those are some ideas to get you started.
EDIT: After reading your comment, the easiest & most light-weight way to do it would be to synchronize using lock, as previously mentioned. That way, only one thread calls the 3rd-party API at a time. Example:
static object APILock = new object(); // global variable
// Do this anytime you need to make calls on this non-thread-safe API:
lock (APILock) {
// call the API; only one thread will run code inside the lock at a time
}
This is generally the accepted way of calling non-thread-safe code.
You can try to use window messages that are (usually) handled by one "main" thread. Create a window, expose wrappers that mimic your API methods to clients, and send window messages internally. When you handle window messages, call your actual implementation.
That is how COM single-thread apartment model works, and it solves exactly the same problem. However, that is quite advanced solution.
Can't your code be refactored in order to make it thread-safe? That would be simpler, I think.

Alternative of Dispatcher class (from .net 3.0) to use in .net 2.0 context

I need an alternative for Dispatcher (.net 3.0) to use for a windows service (done in .net 2.0). Can you give me some idea how to achieve something like that or point me some links?
I know that a dispatcher has a SynchronizationContext behind, but I don't know how I can use a SynchronizationContext into a service.
If you think that I should stick to the Dispatcher (.net 3.0) ... how can I manipulate it (OnServiceStop, OnServiceStart)
edited:
More details (see also...here)
Idea is that I would like to host into my windows service some extensions/plugins which would communicate between each-other through a method ExecuteCommand(type, params).
This method also raises an event to the service in order to receive results if it was executed from inside the plugin. Each plugin could have its own thread from where it calls this method ExecuteCommand so I would like to gather and synchronize all the calls into one thread (main service thread) in order to return the result appropriately.
This is why Dispatcher came into play. But I would like to have, maybe, something in .net 2.0 or do you think Dispatcher is good in my case?
Thanks.
Windows Services don't have anything like the Dispatcher (or message loop in Windows Forms). If you want to marshal from one thread to another, the "target" thread will have to be running its own sort of message loop.
If you could tell us more about what you're trying to achieve, it would make it easier to help you.
EDIT: Okay, it sounds like basically want a producer/consumer queue: one thread waits until something is present in the queue, and processes it. Producers can add to the queue whenever they like.
I have a very simple implementation of a producer/consumer queue in my threading tutorial, but there may be more advanced implementations around. (.NET 4 makes this easy, but it's harder in .NET 2.) If you do take my implementation, you'll want to think about making it generic and adding termination conditions. Joe Albahari has another implementation you should look at, too.

Multithreading: how to update UI to indicate progress

I've been working on the same project now since Christmas 2008. I've been asked to take it from a Console Application (which just prints out trace statements), to a full Windows App. Sure, that's fine. The only thing is there are parts of the App that can take several minutes to almost an hour to run. I need to multithread it to show the user status, or errors. But I have no idea where to begin.
I've aready built a little UI in WPF. It's very basic, but I'd like to expand it as I need to. The app works by selecting a source, choosing a destination, and clicking start. I would like a listbox to update as the process goes along. Much in the same way SQL Server Installs, each step has a green check mark by its name as it completes.
How does a newbie start multithreading? What libraries should I check out? Any advice would be greatly appreciated.
p.s. I'm currently reading about this library, http://www.codeplex.com/smartthreadpool
#Martin: Here is how my app is constructed:
Engine: Runs all major components in pre-defined order
Excel: Library I wrote to wrap COM to open/read/close/save Workbooks
Library: Library which understands different types of workbook formats (5 total)
Business Classes: Classes I've written to translate Excel data and prep it for Access
Db Library: A Library I've written which uses ADO.NET to read in Access data
AppSettings: you get the idea
Serialier: Save data in-case of app crash
I use everything from LINQ to ADO.NET to get data, transform it, and then output it.
My main requirement is that I want to update my UI to indicate progress
#Frank: What happens if something in the Background Worker throws an Exception (handled or otherwise)? How does my application recieve notice?
#Eric Lippert: Yes, I'm investigating that right now. Before I complicate things.
Let me know if you need more info. Currently I've running this application from a Unit Test, so I guess callig it a Console Application isn't true. I use Resharper to do this. I'm the only person right now who uses the app, but I'd like a more attractive interface
I don't think you specify the version of the CLR you are using, but you might check out the "BackgroundWorker" control. It is a simple way to implemented multiple threads.
The best part, is that it is a part of the CLR 2.0 and up
Update in response to your update: If you want to be able to update the progress in the UI -- for example in a progress bar -- the background worker is perfect. It uses an event that I think is called: ProgressChanged to report the status. It is very elegant. Also, keep in mind that you can have as many instances that you need and can execute all the instances at the same time (if needed).
In response to your question: You could easily setup an example project and test for your question. I did find the following, here (under remarks, 2nd paragraph from the caution):
If the operation raises an exception
that your code does not handle, the
BackgroundWorker catches the exception
and passes it into the
RunWorkerCompleted event handler,
where it is exposed as the Error
property of
System.ComponentModel..::.RunWorkerCompletedEventArgs.
Threading in C# from Joseph Albahari is quite good.
This page is quite a good summary of threading.
By the sound of it you probably don't need anything very complex - if you just start the task and then want to know when it has finished, you only need a few lines of code to create a new thread and get it to run your task. Then your UI thread can bumble along and check periodically if the task has completed.
Concurrent Programming on Windows is THE best book in the existence on the subject. Written by Joe Duffy, famous Microsoft Guru of multithreading. Everything you ever need to know and more, from the way Windows thread scheduler works to .NET Parallels Extensions Library.
Remember to create your delegates to update the UI so you don't get cross-threading issues and the UI doesn't appear to freeze/lockup
Also if you need a lot of notes/power points/etc etc
Might I suggest all the lecture notes from my undergrad
http://ist.psu.edu/courses/SP04/ist411/lectures.html
The best way for a total newcomer to threading is probably the threadpool. We'll probably need to know a little more about these parts to make more in depth recommendations
EDIT::
Since we now have a little more info, I'm going to stick with my previous answer, it looks like you have a loads of tasks which need doing, the best way to do a load of tasks is to add them to the threadpool and then just keep checking if they're done, if tasks need to be done in a specific order then you can simply add the next one as the previous one finishes. The threadpool really is rather good for this kind of thing and I see no reason not to use it in this case
Jason's link is a good article. Things you need to be aware of are that the UI can only be updated by the main UI thread, you will get cross threading exceptions if you try to do it in the worker thread. The BackgroundWorker control can help you there with the events, but you should also know about Control.Invoke (or Control.Begin/EndInvoke). This can be used to execute delegates in the context of the UI thread.
Also you should read up on the gotchas of accessing the same code/variables from different threads, some of these issues can lead to bugs that are intermittent and tricky to track down.
One point to note is that the volatile keyword only guarantees 'freshness' of variable access, for example, it guarantees that each read and write of the variable will be from main memory, and not from a thread or processor cache or other 'feature' of the memory model. It doesnt stop issues like a thread being interrupted by another thread during its read-update-write process (e.g. changing the variables value). This causes errors where the 2 threads have different (or the same) values for the variable, and can lead to things like values being lost, 2 threads having the same value for the variable when they should have different values, etc. You should use a lock/monitor (or other thread sync method, wait handles, interlockedincrement/decrement etc) to prevent these types of problems, which guarantee only one thread can access the variable. (Monitor also has the advantage that it implicitly performs volatile read/write)
And as someone else has noted, you also should try to avoid blocking your UI thread whilst waiting for background threads to complete, otherwise your UI will become unresponsive. You can do this by having your worker threads raise events that your UI subscribes to that indicate progress or completion.
Matt
Typemock have a new tool called Racer for helping with Multithreading issues. It’s a bit advanced but you can get help on their forum and in other online forums (one that strangely comes to mind is stackoverflow :-) )
I'm a newbie to multithreading as well, but I agree with Frank that a background worker is probably your best options. It works through event subscriptions. Here's the basics of how you used it.
First Instantiate a new background worker
Subscribed methods in your code to the background workers major events:
DoWork: This should contain whatever code that takes a long time to process
ProgressChanged: This is envoked whenever you call ReportProgress() from inside the method subscribed to DoWork
RunWorkerCompleted: Envoked when the DoWork method has completed
When you are ready to run your time consuming process you call the RunAsync() method of the background worker. This starts DoWork method on a separate thread, which can then report it's progress back through the ProgressChanged event. Once it completed RunWorkerComplete will be evoked.
The DoWork event method can also check if the user somehow requested that the process be canceled (CanceLAsync() was called)) by checking the value of the CancelPending property.

Categories

Resources