Non-Blocking Threading - c#

I am re-factoring a C# project that is used by several full-sized applications. This class interacts with hardware and often takes hundreds of milliseconds or more to execute some commands. In many cases, I am replacing Thread.Wait() calls that the previous programmer wrote with ThreadPool calls to perform these actions.
Now, some of the functions this project provides to the several projects using it take hundreds of milliseconds or more to execute and return a value to the calling program that the program must use. My question is whether or not there is some mechanism that I may use within this project to make these calls execute and return on some thread other than the main thread? In other words, I want to make these methods non-blocking from the perspective of this project, rather than require other applications using these functions to place calls in a separate thread.
Thanks

In other words, I want to make these methods non-blocking from the perspective of this project, rather than require other applications using these functions to place calls in a separate thread.
In general, the best approach is often to return a Task<T> in this type of scenario. This allows the caller to block if necessary, or use the new await and async keywords to cleanly coordinate with your library, without blocking or forcing them to move to a separate thread.

If you are using .net 4.5 you can use Task.Run to execute the slow operations on a separate thread and then ConfigureAwait(false) to not execute on the main thread once they return.
Task.Run(() => <slow operatoion).ConfigureAwait(false);

Not knowing what version of the framework you're using, have a look at the begin/end async pattern. You should look at changing the API for the project to implement it.
http://msdn.microsoft.com/en-us/library/ms228963.aspx

i worked on similar stuff ... i would suggest you to use 'select' instead of using threading.... look at this ... if it helps you
http://www.kegel.com/c10k.html

Related

Making third party I/O DLL asynchronous

I need to use a third-party DLL which implements a TCP socket client (in C++) using blocking calls. So basically (pseudocode);
void DoRequest()
{
send(myblockingSocket,data);
recv(myblockingSocket,responsedata);
}
What is the recommended way to make these calls accessible in .NET as asynchronous calls using async-await (without changing the original DLL) ?
I read: https://learn.microsoft.com/en-us/dotnet/standard/async-in-depth#deeper-dive-into-tasks-for-an-io-bound-operation and https://learn.microsoft.com/en-us/dotnet/csharp/async and several other pages and did not find another solution than spawning a new task, which is not recommended to do on I/O bound operations because of the task creation overhead.
What is the recommended way to make these calls accessible in .NET as asynchronous calls using async-await (without changing the original DLL) ?
There is no recommended solution because this isn't possible. Either the DLL itself must be changed/replaced so that it supports asynchrony, or the asynchronous calls will just be running the synchronous code on a background thread - what I call "fake asynchrony" because it appears asynchronous but is actually taking up a thread anyway.
... did not find another solution than spawning a new task, which is not recommended to do on I/O bound operations because of the task creation overhead.
It's actually not recommended for a couple of reasons:
It lies to the upstream code. It says "this API is asynchronous" when it's not. This can lead consumers to make incorrect decisions, e.g., preferring the asynchronous API in a server scenario.
It doesn't provide any actual benefit. Implementing a method with Task.Run forces the consumers to use an additional thread. If you just kept the API synchronous, then consumers can choose to call it with Task.Run or not, depending on their needs.

Using ThreadPool threads in library

I'm working on a .net core library that will get used mostly in web apps. This library is being built with performance in mind as this is the main design decision. There is some code that is fairly heavy and due to this, will get cached so that subsequent calls are quick. As you can imagine, the first call is slower and I don't want that. I want to execute this code at the earliest possible time to warm up the cache without affecting the other operations. I was thinking of using Task.Start() without awaiting to to achieve this.
My question is, is it frowned upon to use threadpool threads in a library, i.e what is the etiquette on this? As this will be mostly used on web apps, I feel I don't want to interfere with the client's threadpool. That being said, the library will only use one background thread and this will be less than a second. Or should I just let the client take the performance hit for first calls?
If I understand you correctly; it's perfectly legitimate to use multi-threading in a library; as a matter of fact: it happens all the time.
Basically, a lot of async Task methods do this in one way or another. (Sometimes there is no thread)
If it's so heavy you need multiple parallel threads for a long period in time, than it's best to create an explicit initialize routine, and warn the caller in the docs.
Task.Run is typically used for such processing.

Clarification on tasks in .net

I'm trying to understand tasks in .net from what I understand is that they are better than threads because they represent work that needs to get done and when there is a idle thread it just gets picked up and worked on allowing the full cpu to be utilized.
I see the Task<ActionResult> all over a new mvc 5 project and I would like to know why this is happening?
Does it make sense to always do this, or just when there can be blocking work in the function?
I'm guessing since this does act like a thread there is still sync objects that may be needed is this correct?
MVC 5 uses Task<ActionResult> to allow it to be fully asynchronous. By using Task<T>, the methods can be implemented using the new async and await language features, which allows you to compose asynchronous IO functions with MVC in a simple manner.
When working with MVC, in general, the Task<T> will hopefully not be using threads - they'll be composing asynchronous operations (typically IO bound work). Using threads on a server, in general, will reduce your overall scalability.
A Task does not represent a thread, even logically. It's not just an alternate implementation of threads. It's a higher level concept. A Task is the representation of an asynchronous operation that will complete at some point (usually in the future).
That task could represent code being run on another thread, it could represent some asynchronous IO operation that relies on OS interrupts to (indirectly, through a few other layers of indirection) cause the task to be marked completed), it could be the result of two other tasks being completed, or the continuation of some other task being completed, it could be an indication of when an event next fires, or some custom TaskCompletionSource that has who knows what as its implementation.
But you don't need to worry about all of those options. That's the point. In other models you need to treat all of those different types of asynchronous operations differently, complicating your asynchronous programs. The use of Task allows you to write code that can easily be composed with any and every type of asynchronous operation.
I'm guessing since this does act like a thread there is still sync objects that may be needed is this correct?
Technically, yes. There are times where you may need to use these, but largely, no. Ideally, if you're using idiomatic practices, you can avoid this, at least in most cases. Generally when one task depends on code running in other tasks it should be the continuation of that task, and information is assessed between tasks through the tasks' Result property. The use of Result doesn't require any synchronization mechanisms, so usually you can avoid them entirely.
I see the Task all over a new mvc 5 project and I would like to know why this is happening?
When you're going to make something asynchronous it generally makes sense to make everything asynchronous (or nothing). Mixing and matching just...doesn't work. Asynchronous code relies on having every method take very little time to execute so that the message pump can get back to processing its queue of pending tasks/continuations. Mixing asynchronous code and synchronous code makes it very likely to deadlock your application, and also defeats most of the purposes of using asynchrony to begin with (which is to avoid blocking threads).

Proper use of DoEvents() that compatible with WPF

Since VB6 I rarely use the method DoEvents() in C#.
I need to use the same function now for same purpose
I notice that people use this function (Application.DoEvents Method ):
Application.DoEvents()
but this suits Windows Forms.
Now I'm working with WPF.
Is there a similar method in WPF?
Or maybe I shouldn't use this method anymore?
Thanks.
Or maybe I shouldn't use this method anymore?
This.
Basically, the use of Application.DoEvents() is almost always an indication that you've got a long-running task which should be executed on a different thread, calling back to the UI thread where UI access is required.
Application.DoEvents() is basically a hack people use when they don't want to take the time to do things properly - at least in the vast majority of cases.
There are various ways of writing long-running tasks which interact with the UI, depending on which versions of the language/framework you're using, and what your long-running task consists of. Options to consider:
Explicitly creating a new thread
Explicitly using the thread pool
Using BackgroundWorker
Using the Task Parallel Library (TPL) - requires .NET 4+
Using asynchronous APIs, which is much simpler as of .NET 4.5 / C# 5

Creating an async method in .NET 4.0 that can be used with "await" in .NET 4.5

I have a .NET project that uses C# in .NET 4.0 and VS2010.
What I would like to do is add some async overloads to my library to make doing async programming easier for users in .NET 4.5 with the await keyword. Right now the methods that are being overloaded are non-asynchronous. Also I don't want to use any async methods myself, just create new ones and make them available.
Is creating async methods in .NET 4.0 and VS2010 possible and if so, what should the .NET 4.0 async method look like?
Because I'm using VS2010 I don't have access to the "async" keyword so what needs to happen to emulate that behavior in .NET 4.0? For example does it need to return any particular type, and does any code need to happen inside the method to make the currently non-asynchronous code it is calling happen asynchronously?
As others have stated, you start by having a method return Task or Task<TResult>. This is sufficient to await its result in .NET 4.5.
To have your method fit in as well as possible with future asynchronous code, follow the guidelines in the Task-based Asynchronous Pattern document (also available on MSDN). It provides naming conventions and parameter recommendations, e.g., for supporting cancellation.
For the implementation of your method, you have a few choices:
If you have existing IAsyncResult-based asynchronous methods, use Task.Factory.FromAsync.
If you have another asynchronous system, use TaskCompletionSource<TResult>.
The simplest way to do this is to return a Task or a Task<T>. That will be enough.
However this only makes sense if your method really executes asynchronously.
I also recommend that you follow the usual pattern of naming them like AbcAsync ("Async" suffix). Your callers will not notice any difference to an async method created with C# 5 (because there is none).
Tip: Just adding async to the method does nothing. Your method will execute sequentially and return a completed task. Making the method return a task must serve a certain purpose - usually this is done because the method inherently executes asynchronously (like a web-service call or file IO).
If your method only contains computation but no IO (or only blocking IO) it is usually better not to make it async because you gain nothing doing that. Async methods do not always execute on a separate thread. If that last sentence surprised you, you may want to dig a little into this topic.
As long as you return a Task that completes somehow (whether in a thread or asynchronously), you would support the async model..
Having a Task execute asynchronously is another story. If you had access to the async keyword and the API you could simply base your method on async calls to other, already supplied async methods. But in this case, you have to hand-craft your async Tasks.
There might be better ways to do it, but the most elegant way I can see (and have used) is to utilize System.Threading.Tasks.TaskCompletionSource to construct a task, use Begin/End model of asynchronous methods to execute whatever you need to execute. Then, when you have the result on hand, post it to the previously constructed Task instance using your completion source.
It will certainly be asynchronous, just not as fancy as the ones in upcoming release.
Disclaimer: I'm no way near an expert on this. Just made some experiments on.

Categories

Resources