What is recommended way to perform async tasks in WPF? - c#

Are there any standard tools, or recommended approaches for async tasks execution?
UPD I understand, how to use threads. I only need to know the recommended WPF way to block UI while performing async call, and how to update progress info.

You can use several ways, for example:
Thread pool
Background Worker
Plain old threads
And since .NET 4, the preferred way is to use Tasks.

Have a look at below post, it describes a way to create an async delegate command(using BackgroundWorker). I have used this kind of command in our application and it works fine and at the same time it provides a consistent way of doing things asynchronously.
An Asynchronous Delegate Command for
your WPF MVVM Apps -
AsyncDelegateCommand
http://amazedsaint.blogspot.com/2010/10/asynchronous-delegate-command-for-your.html
A similar implementation is also mentioned here -
Asynchronous WPF Commands

depends what you are trying to do async.
e.g. calling a WCF service I'd use the build-in way, with the Completed pattern that does the marshalling for you.
Normal Background work I'd use the BackgroundWorker as you again don't need to worry about the marshalling.

In addition to standard threads. One thing to use are Async methods of many classes, that can do it. This includes web service requests, file read/write operations.
One thing to look at is Coroutines, used mainly by Caliburn.Micro . But its not standard way to do it.
Also .NET 4 adds Task class along with ParallelExtensions, that is capable to do some async programming easier. But its still clumsy, so .NET 5 adds async programing model, to make thigs even easier. But god knows when its going to be released.

Related

what is the difference betweent Task.Run and System.Threading.ThreadPool.RunAsync?

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

How do I write an async wrapper around a third party IO library in C#

I need to use a library that provides access to its own database. Unfortunately, all methods are classic synchronous. I'd prefer to have async methods to offload the IO load like we already have for say SQL Server.
I understand this is a very generic question without much concrete information. Are there any means to move to that point or is it just too bad?
Examples and/or links would be much appreciated.
If there's some form of asynchronous API in the library you are using you can use it to manufacture async API with TaskCompletionSource<T>. It can be BeginX/EndX, DoX with a XCompleted event or any other form.
If nothing like that exists, you simply can't create truly asynchronous overloads. You can offload these synchronous calls to a ThreadPool thread using Task.Run but that would only help with responsiveness and not with performance in any way.

How many models of Asynchronous development in .NET?

I am learning asynchronous programming using C# and I usually use BeginInvoke, but I am not very sure about the other methods of creating asynchronous application.
I have asked a question about this,see below link for more details:
How to return T value from BeginInvoke?
In above link, Gravell said that there are four models of asynchronous development
There's at least 4, then - a regular callback (non-APM, non-EAP) is also not uncommon
But Overflow said that there are three:
There are 3 models of asynchronous development in .NET
APM - (BeginXXX / EndXXX) which you are using here, when the long running task completes, it calls back into your code in the EndXXX method
EAP - Event based. In this model, when the long running task completes, an event is raised to inform your code.
TPL - New in .NET 4, this is the Task-based version. It looks most like synchronous programming to client code, using a fluent interface. Its calls back to your code using ContinueWith.
Anyone can help me on this?
I have searched google.com a lot, but actually they are using BeginInvoke most. thanks for your help.
Thread.Start - brutal
delegate.BeginInvoke/EndInvoke - 'old' standard
ThreadPool.QueueUserWorkItem - smart
TaskFactory.StartNew - the only way to do it correct (according to Patterns of parallel programming book | i recommend you to read it first for disambiguation)
There's a lot that can be caught in the term "asynchronous development."
For one, you could want to execute code on a background thread. I recently updated a blog post of mine contrasting several common approaches to executing code in the background. Here's the list, in order from most desirable to least:
Task (as used by async/await).
Task (as used by the Task Parallel Library).
BackgroundWorker.
Delegate.BeginInvoke.
ThreadPool.QueueUserWorkItem.
Thread
On another hand, you could want to represent an asynchronous operation (which may or may not be actual code executing on a background thread). In that case, there are several approaches, in order from most desirable to least:
Task (in the style of the Task-based Asynchronous Pattern (TAP))
IAsyncResult with Begin*/End* methods (which has the unfortunate name Asynchronous Programming Model (APM)).
A component written using the Event-based Asynchronous Pattern (EAP).
(As a side note, BackgroundWorker is EAP, and Delegate.BeginInvoke is APM).
On another hand, you could mean asynchronous programming in general, which can be interpreted to mean a reactive approach. In this case, there are only two approaches that I know of:
Reactive Extensions (Rx).
Event-based Asynchronous Pattern (EAP).
However, you could make a case that any event-driven program is reactive to some extent, so just handling UI events is a (simple) form of "asynchronous programming."
Also, these are only the common models. Any platform or library can add more. Here's some off the top of my head:
The Socket class has a special form of APM that can be used to minimize memory allocations. It works very similarly to APM but does not fit the pattern.
The WinRT runtime (coming in Windows 8) has its own representations of asynchronous operations (IAsyncOperation<TResult> and IAsyncInfo).
Windows Phone has specific support for a background agent, which permits you to run code in the background even if your app isn't currently running.
It will most certainly be useful to learn the methods Mikant described for asynchronous development. Just wanted to give you a heads up though that C# 5.0 is completely redesigning how the language deals with async. This will be its main theme along with introducing two new keywords, async and await. You simply call await on a long-running task and it will begin the task and return control to the calling method. Once the task is complete it proceeds with the rest of the code.
Here is an excellent video for the full details of its usage and explanation. It not only describes the old way of performing async operations but a complete review of the new style. It makes writing async applications a ton easier and much more readable with a natural flow.
This is the future of C# async behavior so well worth learning.
http://channel9.msdn.com/events/PDC/PDC10/FT09/

C# Multi-Threading - What method to use?

My goal is to write a program that handles an arbitrary number of tasks based on given user input.
Let's say the # of tasks are 1000 in this case.
Now, I'd like to be able to have a dynamic number of threads that are spawned and start handling the tasks one by one.
I would assume I need to use a "synchronous" method, as opposed to a "asynchronous" one, so that in case one tasks has a problem, I wouldn't want it to slow down the completion of the rest.
What method would I use to accomplish the above? Semaphores? ThreadPools? And how do I make sure that a thread does not try to start a task that is already being handled by another thread? Would a "lock" handle this?
Code examples and/or links to sites that will point me in the right direction will be appreciated.
edit: The problem with the MSDN Fibonacci example is that the waitall method can only handle up to 64 waits. I need more than that due to the 1000 tasks. How to fix that situation without creating deadlocks?
Are these tasks independent? If so, you basically want a producer/consumer queue or a custom threadpool, which are effectively different views on the same thing. You need to be able to place tasks in a queue, and have multiple threads be able to read from that queue.
I have a custom threadpool in MiscUtil or there's a simple (nongeneric due to age) producer/consumer queue in my threading tutorial (about half way down this page).
If these tasks are reasonably long-running, I wouldn't use the system threadpool for this - it will spawn more threads than you probably want. If you're using .NET 4.0 beta 1 you could use Parallel Extensions though.
I'm not quite sure about your comment on WaitAll... are you trying to work out when everything's finished? In the producer/consumer queue case, that would probably involve having some sort of "stop" entry in the queue (e.g. null references which the consuming threads would understand to mean "quit") and then add a "WaitUntilEmpty" method (which should be fairly easy to implement). Note that you wouldn't need to wait until the last items had been processed, as they'd all be stop signals... by the time the queue has emptied, all the real work items will definitely have been processed anyway.
You'll probably want to use the ThreadPool to manage this.
I recommend reading up on MSDN on How to use the ThreadPool in C#. It covers many aspects of this, including firing tasks, and simple synchronization.
Using Threading in C# is the main section, and will cover other options.
If you happen to be using VS 2010 beta, and targetting .NET 4, the Task Parallel Library is a very good option for this - it simplifies some of these patterns.
You can't use it (yet) but the new Task class in .NET 4 would be ideal for this kind of situation.
Until then, the ThreadPool is your best bet. It has a (very) limited form of load-balancing. Note that if you try to start 1000 Threads you will probably get an Out Of Memory exception. The ThreadPool will handle that with ease.
Your sync problem can be handled with a simple (Interlocked) counter, if the timing is such that you can tolerate a Sleep(1) loop in the main thread. The ThreadPool is missing a more convenient way to do this.
A simple strategy to avoid a task is get by two or more thread is a syncronized (with a mutext for example) vector.
See this http://msdn.microsoft.com/en-us/library/yy12yx1f.aspx
Perhaps you can use the BackgroundWorker class. It creates a nice abstraction on top of the thread pool. You can even subclass it if you want to setup many similar jobs.
As has been mentioned, .NET 4 features the excellent Task Parallel Library. But you can use the June 2008 CTP of it in .NET 3.5 just fine. I've been doing this for some hobby projects myself, but if this is a commercial project, you should check out if there are legal issues.

C#: How can i elegantly and or simplistically make cross threaded calls?

i have a tcp server that, when a client connects, it makes a new thread and adds them to it but everytime i try to access information about the connection or anything about it, say even keeping a count of how many clients are connected, i get a cross-thread illegal exception or something like that.
ive read several tutorials on things called delegates, invoking and reflection but all the examples or tutorials simply confuse me as doing one invoke a certain way fails in another.
is there an elegant or simplistic way of doing this? do i need to learn how to do something else first? or am i just making things way more complex than they are? any suggestions, links or tips are most appreciated and accepted.
I suppose you go directly to the UI from your client connection thread. This is not good. Instead, consider using some variation of MVP pattern to decouple presentation logic from views. Thus, your "connection threads" will talk to some intermediary, presenters will talk to the same intermediary and just hand off some data for view to display.
As far as cross-thread operations are concerned, particulary UI thread operations, I find SynchronizationContext to be very useful in cicrumstances when you want to marshal a call from a non-UI thread to the UI thread. See this article for more in-depth discussion.
I guess you get this cross thread exception since you are trying to update screen elements from your threaded code. If you need to do that you can get a simple solution using anonymous method.
Say that you want to add an item to a listbox called ListBoxLog. This code would do the trick from any thread:
ListBoxLog.Invoke((MethodInvoker)delegate { ListBoxLog.Items.Add("Done"); });
There's also a property to check .InvokeRequired you can check to see if invocation is nessecary. You would typically check that property in a function that could be called by both the main UI thread and any background thread.
You can also use BeginInvoke like I did with Invoke. BeginInvoke is totaly asynchronous and does not wait for the code in the delegate to finish.
Using delegates and events.
That would be my best answer.
http://www.codeproject.com/KB/cs/Cross_thread_Events.aspx
There are plenty of examples online to help you:
http://www.google.com/search?q=tcp+server+multi+thread
When using C#, the Concurrency and Coordination Runtime (CCR) also has a sample about implementing multithreaded tcp server. The CCR allows a much better paradigm to implement parrallel processing, it simplifies a lot of the standard multi-threading code.

Categories