I have a bunch of interfaces for a repository in a core class library that defines return types as Task. These interfaces are used in other projects to define async methods.
I need to implement these same interfaces in a Xamarain monodroid project and was wondering how I should use the same return types without using async await since that's not supported yet in MonoDroid. I don't want to modify the existing core library interfaces at all if possible.
Technically, you don't have to use async/await; it's just a lot easier than doing it "by hand". Your implementations just have to return Tasks that are never null and already started (if applicable).
The TAP document has some useful techniques and guidelines. One key type is TaskCompletionSource<TResult> which you can use to wrap any asynchronous implementation (e.g., APM). Synchronous implementations can use Task.FromResult (which is just a small wrapper around TaskCompletionSource. If you have CPU work to do, you can use Task.Factory.StartNew, which is closely related but not quite equivalent to Task.Run. For more complex implementations, you would need continuations a la ContinueWith.
In other words, all the .NET 4.0 TPL techniques can be used, as long as your returned Tasks are always started. (The only way to get an unstarted Task is to construct it with the Task constructor and not call Start. So as long as you don't do this, you should be fine.)
Related
async/await gained a lot of popularity in the C# world the past few years. Async functions also tend to spread rapidly within an application: Awaitables need to be awaited, therefore the calling function must be async and is therefore also an awaitable which needs to be awaited,... and so forth.
I'm using a C# library in a C++/Cli project. The library exposes async APIs. The Visual C++ compiler does not support async/await. Hence I have no way to await any of the APIs the library gives me.
I have the following options:
Call the async function and "letting it go": Not an option since I often need the return values to proceed.
Calling Wait() or accessing the Result property of the Task/Task<T> objects the async function returns: Causes the infamous dead-lock of the UI thread.
Is there any way to make this work? I wouldn't mind executing the async APIs synchronously if I have to.
To me, it sounds like your problem is more of a symptom of a bigger issue. I personally try to avoid as much as I can putting business logic in a C++-CLI module. Specifically, I try to limit a ref class functionality to 3 main areas:
Translating managed method calls to native method calls (that includes transforming parameters if necessary).
Translating native return values to managed return values. This can even be translating an asynchronous function receiving a callback to a method returning Task.
Translating native events (callbacks) to managed events.
I Might be wrong, but in your situation it sounds like your C++ code is not well decoupled and you end up wiring different parts of it inside a C++-CLI module.
As for your question, I would use Task.ContinueWith family of methods to perform the asynchronous continuation instead of async / await. Yet, If you want the continuation to be invoked on a specific SynchronizationContext (such as UI thread) then special care must be taken to supply the right TaskScheduler.
Is it possible to reuse the same Task<T> created with Task.FromResult for instant returning methods (as it is completed already anyway)?
My reasoning behind the question is to reduce garbage produced by implementations of async interfaces that complete instantly (Task<bool> would be a great example for it, as it only has two possible values).
Base on this article about disposing of tasks, it should be possible, if .NET Core behaves the same (does it?).
Yes, and this is actually strongly recommended in cases where you have a small set of likely results that might be known synchronously (from cache, etc). Likewise, in the case of Task (not Task<T>), Task.CompletedTask can be used.
Note that if most of your calls complete synchronously but you do not have a small domain of likely results, you might want to consider ValueTask<T>, which is optimized for this case.
Everything here applies equally to both .NET and .NET Core.
async/await gained a lot of popularity in the C# world the past few years. Async functions also tend to spread rapidly within an application: Awaitables need to be awaited, therefore the calling function must be async and is therefore also an awaitable which needs to be awaited,... and so forth.
I'm using a C# library in a C++/Cli project. The library exposes async APIs. The Visual C++ compiler does not support async/await. Hence I have no way to await any of the APIs the library gives me.
I have the following options:
Call the async function and "letting it go": Not an option since I often need the return values to proceed.
Calling Wait() or accessing the Result property of the Task/Task<T> objects the async function returns: Causes the infamous dead-lock of the UI thread.
Is there any way to make this work? I wouldn't mind executing the async APIs synchronously if I have to.
To me, it sounds like your problem is more of a symptom of a bigger issue. I personally try to avoid as much as I can putting business logic in a C++-CLI module. Specifically, I try to limit a ref class functionality to 3 main areas:
Translating managed method calls to native method calls (that includes transforming parameters if necessary).
Translating native return values to managed return values. This can even be translating an asynchronous function receiving a callback to a method returning Task.
Translating native events (callbacks) to managed events.
I Might be wrong, but in your situation it sounds like your C++ code is not well decoupled and you end up wiring different parts of it inside a C++-CLI module.
As for your question, I would use Task.ContinueWith family of methods to perform the asynchronous continuation instead of async / await. Yet, If you want the continuation to be invoked on a specific SynchronizationContext (such as UI thread) then special care must be taken to supply the right TaskScheduler.
I have a lot of Utils classes that I use for many different projects, most of them are static and made out of static methods that usually don't even call each others.
My intention is to take advantages from the new async/await features but without rewriting everything, so my question is: can I just add a new method for each existing method named MethodAsync with the Task.Run(() => MethodName)?
example:
//old code that will not be removed
static void DoSomething()
{ ... }
//new code that will be added
static async Task DoSomethingAsync()
{
//not really sure if Im supposed to use await/async here.
//isn't Task awaitable even without async??
return await Task.Run(() => DoSomething());
}
Basically in the old code I just had a normal sync method while in the new one I have an async method that could even run in another thread if the CLR see it as a CPU-bound method.
If I correctly understand, every asyncronous method contains by definition an await to an awaitable object which is a Task or another asyncronous method.
that means that whenever I can use an async .NET method, I should await it and mark my caller method as async.
But, every other method that do not call any async method but could take some time to complete should be called with a Task.Run call.
right?
EDIT
so I have read all the posted links, the best practices on msdn and a few blog posts but I still need a complete routine to follow when coding with the new async/await feature.
this is what I get so far:
1) every .NET method that has an async alternative should use the async alternative. (As far as I know the .NET async methods already exists ONLY for methods that can be async).
2) every method that use async methods should be made async too.
3) every method that do not use async methods (cause there aren't available) but still takes some cpu-time to execute should be made async by wrapping them using Task.Run (I understand that in this case it should be the client to use Task.Run if they want but since im only adding these wrappers for methods that takes more than 50ms to execute and there will be still available the non-async version of the method, I still don't see why I shouldn't place this wrapper in the library).
4) every method that takes non-cpu-time cause it's waiting for other sources (like internet, database, events, etc...) should use TaskFactory.FromAsync or TaskCompletionSource.
5) System.Threading.Tasks.Parallel.Invoke(method1, method2, etc...) is now deprecated. From what I read Task.Run already run concurrent threads if the CLR thinks that concurrency is required. So it seems that Task.Run already uses Parallel.Invoke when needed.
I was finally able to find good resources that cleared all my doubts:
the first one is "The Task-based Asynchronous Pattern" available at http://www.microsoft.com/en-us/download/details.aspx?id=19957
This document explains the async/await feature, how/when to use it, it contains many practical examples and a few of very usefull static methods that im now using on every project!
The second one is "The zen of async: Best practices for best performance" available at http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-829T
which is a complete overview of the async feature, with some coverage of the Parallel features and it also explains why it should never be the library that use Task.Run() method but it should be a consumer choice instead.
So in the end I was really confusing multithreading with asynchronous code and I couldn't grasp the advantages of async code because I was just looking at 1 single method at the time while the real benefits of async code can only be seen if the entire project (or at least a consistent portion of it) is written following the async pattern.
For example in asp.net, if there isn't any blocking code (everything written in a async fashion way), then a thread can serve another client while yours is awaiting an async operation, improving scalability, while in a xaml application a thread that launch an async operation can immediately go back to supporting your UI instead of just waiting that operation to be over, improving responsiveness.
This has been discussed in Should I expose asynchronous wrappers for synchronous methods? The part of this article that I thought highlighted why this is bad design is below:
Consider, for example, a simple method like Dictionary<TKey,TValue>.Add(TKey,TValue). This is a really fast method, right? Typically, yes, but remember how dictionary works: it needs to hash the key in order to find the right bucket to put it into, and it needs to check for equality of the key with other entries already in the bucket. Those hashing and equality checks can result in calls to user code, and who knows what those operations do or how long they take. Should every method on dictionary have an asynchronous wrapper exposed? That’s obviously an extreme example, but there are simpler ones, like Regex. The complexity of the regular expression pattern provided to Regex as well as the nature and size of the input string can have significant impact on the running time of matching with Regex, so much so that Regex now supports optional timeouts… should every method on Regex have an asynchronous equivalent? I really hope not.
Obviously I advise you to read the entire article too, but I hope the above highlights a great reason why exposing *Async() methods should not wrap synchronous ones in a library.
I hope this helps.
I found Difference between […]Async and Begin[…] .net asynchronous APIs question but this answer confused me a little bit.
Talking about these patterns, Stephen said:
Most *Async methods (with corresponding *Completed events) are using the Event-Based Asynchronous Pattern. The older (but still perfectly valid) Begin* and End* is a pattern called the Asynchronous Programming Model.
The Socket class is an exception to this rule; its *Async methods do not have any corresponding events; it's essentially just APM done in a way to avoid excessive memory allocations.
I get it as using *Async methods are more efficient, at least when it comes to sockets.
But then he mentioned Task Parallel Library:
However, both APM and EBAP are being replaced with a much more flexible approach based on the Task Parallel Library. Since the TPL can wrap APMs easily, older classes will likely not be updated directly; extension methods are used to provide Task equivalents for the old APM methods.
I found TPL and Traditional .NET Asynchronous Programming on MSDN, I know the basics of TPL, creating tasks, cancellations, continuations, etc but I still fail to understand these:
What are the advantages of Asynchronous Programming Model (APM) and Event-based Asynchronous Pattern (EAP) compared to each other? How does TPL can wrap APMs easily mean that both APM and EAP are being replaced with TPL?
And most importantly: Which should I use in socket programming;
APM?
EAP?
APM or EAP wrapped by a Task?
TPL by using the blocking methods of Socket class in tasks?
Other?
How does TPL can wrap APMs easily mean that both APM and EAP are being replaced with TPL?
It doesn't. Wether APM and EAP will be replaced by TAP (Task Asynchronous Pattern) or not in new APIs has nothing to do with this. I would expect TAP to replace APM and EAP for a variety of reasons. The main reason to me is that the code you write for using the TAP composes much better. Doing .ContinueWith(/* ... */).ContinueWith(/* ... */) generally reads much better than the corresponding code you would need to write to chain async calls through Begin/End methods, even if you don't take into account the options you can pass to ContinueWith to determine if the continuation should run. The TPL also provides various combinators for Tasks, such as WaitAll and WaitAny, that can make some scenarios much easier. The language support coming in C# and VB.NET via the async/await keywords will make this even easier.
Being able to wrap APMs in the TAP makes it easier to switch to this pattern because it means you don't have to rewrite existing code to make it fit in the new model.
Which should I use in socket programming?
I would recommend using the TAP wrapping the APM methods on Socket. Unless you can prove that the extra overhead of wrapping the Begin/End methods into a Task are the difference between scalable/fast enough or not, I would take advantage the ease of coding of the TAP.
Gideon had a great answer; I just wanted to provide some more background:
What are the advantages of Asynchronous Programming Model (APM) and Event-based Asynchronous Pattern (EAP) compared to each other?
APM is more common and it has a pretty strictly-defined pattern. e.g., the TPL has generic wrappers for APM methods (TaskFactory.FromAsync), but it can't do the same for EAP because EAP isn't as strictly-defined.
EAP has one great advantage: the event callbacks handle thread marshaling for you. So they're really nice for, e.g., basic background operations for a UI (BackgroundWorker).
TAP combines the best of both worlds: automatic thread marshaling by default and a strictly-defined, common pattern. It also has a nice object representation for an asynchronous operation (Task).
How does "TPL can wrap APMs easily" mean that "both APM and EAP are being replaced with TPL"?
It doesn't.
"However, both APM and EBAP are being replaced with a much more flexible approach based on the Task Parallel Library." - meaning that new code doesn't need to include APM/EAP methods/events; new code should include TAP methods instead.
"Since the TPL can wrap APMs easily, older classes will likely not be updated directly; extension methods are used to provide Task equivalents for the old APM methods." - meaning that you can add TAP methods to an existing APM type using TaskFactory.FromAsync; I figured the TPL team would take this approach rather than modifying a ton of classes in the BCL. However, I was wrong in this conjecture. For performance reasons, the BCL/TPL team did review the entire framework and added TAP methods directly to .NET classes instead of using extension methods. The new TAP methods are included in .NET 4.5, coming soon...