what is the effect difference of them on threading?
the Task.Run seems still run on the same task manger of current threading, and ThreadPool.RunAsync seems more related less with current threading.
I notice that the Task.Run is easy to automatically capture parameter which is outside it. Such as If the Task.Run call a string object outside it, the Task.Run can automatically capture it.
In general, Task is an abstraction over threads. The main benefit of tasks is that they allow you to focus less on the low-level aspects of multi-threading and simplify things like continuation. They are also very well integrated into C# and are the basis of modern asynchronous programming. UWP API relies on async/await quite heavily, so using Tasks is quite encouraged (although the UWP API itself uses IAsyncOperation for many of its methods as a Task-like type, which is Windows Runtime compatible and can be exposed in WinRT libraries).
The implementation of tasks uses the thread pool under the hood, so in general, unless you need the low-level control, Tasks should be easier to work with.
this is the answer in https://social.msdn.microsoft.com/Forums/en-US/9c18a978-4a87-40e2-9294-1346bcd2d528/difference-between-task-and-threadpool. thanks #aage. In general, when you're using managed code, you'll want to use Task.Run as it targets the CLR thread pool. ThreadPool.RunAsync runs in native code and targets the Windows thread pool.
https://social.msdn.microsoft.com/Forums/en-US/9c18a978-4a87-40e2-9294-1346bcd2d528/difference-between-task-and-threadpool
Related
I have a quad core PC.
I had considered programmatically of uterlising multi-core processing using the Task Parallel Library. However, when I Googled for examples I was informed that the CPU will handle this automatically and is best to leave it alone.
Now, I find another article singing the praises of this library on Code Project.
Is there any advantage to using this library?
thanks
Unless your application is actively taking advantage of parallel processing, neither the OS nor the CPU will do this for you automatically. The OS and CPU may switch execution of your application between multiple cores, but that does not make it execute simultaneously on the different cores. For that you need to make your application capable of executing at least parts in parallel.
According to MSDN Parallel Processing and Concurrency in the .NET Framework there are basically three ways to do parallel processing in .NET:
Managed threading where you handle the threads and their synchronization yourself.
Various asynchronous programming patterns.
Parallel Programming in the .NET Framework of which both the Task Parallel Library and PLINQ are a part.
Reasons for using the TPL include that it and the accompanying tools according to the MSDN article
simplify parallel development so that you can write efficient, fine-grained, and scalable parallel code in a natural idiom without having to work directly with threads or the thread pool.
Threads vs. Tasks has some help for deciding between threads and the TPL
with the conclusion:
The bottom line is that Task is almost always the best option; it provides a much more powerful API and avoids wasting OS threads.
The only reasons to explicitly create your own Threads in modern code are setting per-thread options, or maintaining a persistent thread that needs to maintain its own identity.
Task parallel Library conducts its act through Task Schedulers .You can configure your TPL to which scheduler it uses. You can write your custom task scheduler which can create one thread for one task. This way you can have configuration advantage over managing your thread . Sth similar to advantage of using Dependency Injection framework over DIY-DI.
And there are already many SO entries for difference between task and Thread
Task vs Thread
Task vs Thread
Multithreading or TPL
I'm joining a C# project in which the developers are heavily using Fibers. Before this project I haven't even heard of them and previously used async await and Threads and BackgroundWorkers to my multitasking operations. Today I was asking them why they used Fibers and the main developer said that it's easier for him to debug. Meaning he knows which thread a particular function has come from and even could access the variables higher in the stack.
I was wondering what are the advantages and disadvantages of using Fibers vs using the new async await and using Threads.
PS: We're using .Net 4.5
I was asking them why they used Fibers and the main developer said
that it's easier for him to debug. Meaning he knows which thread a
particular function has come from and even could access the variables
higher in the stack.
That sounds outright peculiar. When using the Task Parallel Library with custom schedulers other than the default ThreadPoolTaskScheduler, you can, yourself, decide how your tasks get scheduled (and it isn't necessarily on new threads). async-await on the other hand provides you a convenient way of doing asynchronous IO. VS gives you the ability to debug asynchronous code using as if it were executing synchronously.
In order to use fibers, one would have to invoke unmanaged API's, as .NET doesn't offer any managed wrappers in the BCL. Even the docs of fibers clearly say there isn't a clear advantage to using them:
In general, fibers do not provide advantages over a well-designed
multithreaded application. However, using fibers can make it easier to
port applications that were designed to schedule their own threads.
I was wondering what are the advantages and disadvantages of using
Fibers vs using the new async await and using Threads.
Using async-await give you the benefit of doing IO bound asynchronous work while feeling like you're executing synchronously. The Task Parallel Library provides an easy way of scheduling work on dedicated threads, be them thread-pool threads or new threads, while allowing you to hook into the mechanism which schedule those units of work. I really see no advantage in using fibers today, with all the framework has to offer.
I think you should tell your main-developer to do some reading on multi-threaded and asynchronous IO work using the Task Parallel Library and async-await, respectively. I think it would make life easier for all of you.
I'm really confused about async-awaits, pools and threads. The main problem starts with this question: "What can I do when I have to handle 10k socket I/O?" (aka The C10k Problem).
First, I tried to make a custom pooling architecture with threads
that uses one main Queue and multiple Threads to process all
incoming datas. It was a great experience about understanding
thread-safety and multi-threading but thread is an overkill
with async-await nowadays.
Later, I implemented a simple architecture with async-await but I
can't understand why "The async and await keywords don't cause
additional threads to be created." (from MSDN)? I think there
must be some threads to do jobs like BackgroundWorker.
Finally, I implemented another architecture with ThreadPool and it
looks like my first custom pooling.
Now, I think there should be someone else with me who confused about handling The C10k. My project is a dedicated (central) server for my game project that is hub/lobby server like MCSG's lobbies or COD's matchmaking servers. I'll do the login operations, game server command executions/queries and information serving (like version, patch).
Last part might be more specific about my project but I really need some good suggestions about real world solutions about multiple (heavy) data handling.
(Also yes, 1k-10k-100k connection handling depending on server hardware but this is a general question)
The key point: Choosing Between the Task Parallel Library and the ThreadPool (MSDN Blog)
[ADDITIONAL] Good (basic) things to read who wants to understand what are we talking about:
Threads
Async, Await
ThreadPool
BackgroundWorker
async/await is roughly analogous to the "Serve many clients with each thread, and use asynchronous I/O and completion notification" approach in your referenced article.
While async and await by themselves do not cause any additional threads, they will make use of thread pool threads if an async method resumes on a thread pool context. Note that the async interaction with ThreadPool is highly optimized; it is very doubtful that you can use Thread or ThreadPool to get the same performance (with a reasonable time for development).
If you can, I'd recommend using an existing protocol - e.g., SignalR. This will greatly simplify your code, since there are many (many) pitfalls to writing your own TCP/IP protocol. SignalR can be self-hosted or hosted on ASP.NET.
No. If we use asynchronous programming pattern that .NET introduced in 4.5, in most of the cases we need not to create manual thread by us. The compiler does the difficult work that the developer used to do. Creating a new thread is costly, it takes time. Unless we need to control a thread, then “Task-based Asynchronous Pattern (TAP)” and “Task Parallel Library (TPL)” is good enough for asynchronous and parallel programming. TAP and TPL uses Task. In general Task uses the thread from ThreadPool(A thread pool is a collection of threads already created and maintained by .NET framework. If we use Task, most of the cases we need not to use thread pool directly. A thread can do many more useful things. You can read more about Thread Pooling
You can avoid performance bottlenecks and enhance the overall responsiveness of your application by using asynchronous programming. Asynchrony is essential for activities that are potentially blocking, such as when your application accesses the web. Access to a web resource sometimes is slow or delayed. If such an activity is blocked within a synchronous process, the entire application must wait. In an asynchronous process, the application can continue with other work that doesn't depend on the web resource until the potentially blocking task finishes.
Await is specifically designed to deal with something taking time, most typically an I/O request. Which traditionally was done with a callback when the I/O request was complete. Writing code that relies on these callbacks is quite difficult, await greatly simplifies it. Await just takes care of dealing with the delay, it doesn't otherwise do anything that a thread does. The await expression, what's at the right of the await keyword, is what gets the job done. You can use Async with any method that returns a Task. The XxxxAsync() methods are just precooked ones in the .NET framework for common operations that take time. Like downloading data from a web server.
I would recommend you to read Asynchronous Programming with Async and Await
I've been reading a lot about async and await, and at first I didn't get it because I didn't properly understand threading or tasks. But after getting to grips with both I wonder: why use async/await if you're comfortable with threads?
The asynchronousy of async/await can be done with Thread signaling, or Thread.Join() etc. Is it merely for time saving coding and "less" hassle?
Yes, it is a syntactic sugar that makes dealing with threads much easier, it also makes the code easier to maintain, because the thread management is done by run-time. await release the thread immediately and allows that thread or another one to pick up where it left off, even if done on the main thread.
Like other abstractions, if you want complete control over the mechanisms under the covers, then you are still free to implement similar logic using thread signaling, etc.
If you are interested in seeing what async/await produces then you can use Reflector or ILSpy to decompile the generated code.
Read What does async & await generate? for a description of what C# 5.0 is doing on your behalf.
If await was just calling Task.Wait we wouldn't need special syntax and new APIs for that. The major difference is that async/await releases the current thread completely while waiting for completion. During an async IO there is no thread involved at all. The IO is just a small data structure inside of the kernel.
async/await uses callback-based waiting under the hood and makes all its nastiness (think of JavaScript callbacks...) go a way.
Note, that async does not just move the work to a background thread (in general). It releases all threads involved.
Comparing async and await with threads is like comparing apples and pipe wrenches. From 10,000 feet they may look similar, but they are very different solutions to very different problems.
async and await are all about asynchronous programming; specifically, allowing a method to pause itself while it's waiting for some operation. When the method pauses, it returns to its caller (usually returning a task, which is completed when the method completes).
I assume you're familiar with threading, which is about managing threads. The closest parallel to a thread in the async world is Task.Run, which starts executing some code on a background thread and returns a task which is completed when that code completes.
async and await were carefully designed to be thread-agnostic. So they work quite well in the UI thread of WPF/Win8/WinForms/Silverlight/WP apps, keeping the UI thread responsive without tying up thread pool resources. They also work quite well in multithreaded scenarios such as ASP.NET.
If you're looking for a good intro to async/await, I wrote up one on my blog which has links to additional recommended reading.
There is a difference between the Threads and async/await feature.
Think about a situation, where you are calling a network to get some data from network. Here the Thread which is calling the Network Driver (probably running in some svchost process) keeps itself blocked, and consumes resources.
In case of Async/await, if the call is not network bound, it wraps the entire call into a callback using SynchronizationContext which is capable of getting callback from external process. This frees the Thread and the Thread will be available for other things to consume.
Asynchrony and Concurrency are two different thing, the former is just calling something in async mode while the later is really cpu bound. Threads are generally better when you need concurrency.
I have written a blog long ago describing these features .
C# 5.0 vNext - New Asynchronous Pattern
async/await does not use threads; that's one of the big advantages. It keeps your application responsive without the added complexity and overhead inherent in threads.
The purpose is to make it easy to keep an application responsive when dealing with long-running, I/O intensive operations. For example, it's great if you have to download a bunch of data from a web site, or read files from disk. Spinning up a new thread (or threads) is overkill in those cases.
The general rule is to use threads via Task.Run when dealing with CPU-bound operations, and async/await when dealing with I/O bound operations.
Stephen Toub has a great blog post on async/await that I recommend you read.
For example a scenario in Winform where the UI thread will be blocked while we use
HttpWebRequest synchronously which in turn requests resources on Internet. Here we can use async method to execute the method while await keyword for certain task allows user to interact with winform even though the request is still running.
This can even be achieved by delegation so what's the advantage of Async Feature?
One of the nicest advantages in my opinion is a more concise way to understand the async programming pattern with less lines of code. If you want to see more clearly how it works, check out this question answered by Jon Skeet: How does Task<int> become a int?
The async and await termonoligy is much simpler and you can basicaly write your code just as you would do a syncronious application by just adding some keywords.
From MSDN:
You can avoid performance bottlenecks and enhance the overall
responsiveness of your application by using asynchronous programming.
However, traditional techniques for writing asynchronous applications
can be complicated, making them difficult to write, debug, and
maintain.
Visual Studio 2012 introduces a simplified approach, async
programming, that leverages asynchronous support in the .NET Framework
4.5 and the Windows Runtime. The compiler does the difficult work that the developer used to do, and your application retains a logical
structure that resembles synchronous code. As a result, you get all
the advantages of asynchronous programming with a fraction of the
effort.
http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx
I assume by "delegation" you mean to call the synchronous methods from a background thread.
As others have pointed out, the code is easier to read and write using async and await, but there's another important difference as well.
When you use synchronous methods, the calling thread is blocked until the operation is complete.
When you use synchronous methods from a background thread, the UI thread is not blocked but the background thread still is.
When you use asynchronous methods, no threads are blocked. This allows more efficient usage of your resources, with less pressure on the thread pool.