When to use TaskFactory in Asp.Net Web applications (webform or mvc)? - asp.net

I am working in WPF now...here we use Background_Worker,TaskFactory.StartNew functions and async/await.
In web apps I know that we have AJAX, MVC partial views etc.
My question is do we really use above mentioned async methods (Tasks, sync/await) in Web apps ? If we use, could you give me some examples ?
I have a document generation module in my web app in which I have to fetch data from DB and create documents out of it. Is it a good scenario for async calls? (to call the function and throw..and never care about it).

I am working in WPF now...here we use Background_Worker,TaskFactory.StartNew functions and async/await.
You really should be using Task.Run instead of BackgroundWorker and Task.Factory.StartNew. Task.Run has much better defaults than StartNew, and is more composable and type-safe than BackgroundWorker.
My question is do we really use above mentioned async methods (Tasks, sync/await) in Web apps ?
On ASP.NET, you should almost never use your own background threads (BackgroundWorker, StartNew, Task.Run). However, you certainly can use async and await.
If we use, could you give me some examples ? I have a document generation module in my web app in which I have to fetch data from DB and create documents out of it.
Yes, database queries are one example of an I/O-based operation. So is "writing" documents - whether as uploads to cloud storage or to the local file system.
I have an MSDN article on async ASP.NET that you may find useful.

Async is useful any time you have disk/database/network I/O. It allows you to do other things while you wait for the I/O to complete, which can result in significant savings. Async isn't really useful for normal CPU bound operations, because of the increased overhead of making it async.
This holds true in WPF as well web applications.
If you want to see a concrete example, Scott Hanselman has a blog entry entitled The Magic of using Asynchronous Methods in ASP.NET 4.5 plus an important gotcha which you may find very interesting.

Related

Asynchronous Database Access Layer in PureMVC

I'm trying to refactor an existing project into PureMVC. This is an Adobe AIR desktop app taking advantage of the SQLite library included with AIR and building upon it with a few other libraries:
Paul Robertson's excellent async SQLRunner
promise-as3 implementation of asynchronous promises
websql-js documentation for good measure
I made my current implementation of the database similar to websql-js's promise based SQL access layer and it works pretty well, however I am struggling to see how it can work in PureMVC.
Currently, I have my VOs that will be paired with DAOs (data access objects) for database access. Where I'm stuck is how to track the dbFile and sqlRunner instances across the entire program. The DAOs will need to know about the sqlRunner, or at the very least, the dbFile. Should the sqlRunner be treated as singleton-esque? Or created for every database query?
Finally, how do I expose the dbFile or sqlRunner to the DAOs? In my head right now I see keeping these in a DatabaseProxy that would be exposed to other proxies, and instantiate DAOs when needed. What about a DAO factory pattern?
I'm very new to PureMVC but I really like the structure and separation of roles. Please don't hesitate to tell me if this implementation simply will not work.
Typically in PureMVC you would use a Proxy to fetch remote data and populate the VOs used by your View, so in that respect your proposed architecture sounds fine.
DAOs are not a pattern I've ever seen used in conjunction with PureMVC (which is not to say that nobody does or should). However, if I was setting out to write a crud application in PureMVC, I would probably think in terms of a Proxy (or proxies) to read information from the database, and Commands to write it back.

WebApi loggin results async

I am using WebApi with Entity Framework to implement a REST service. I need to log the usage to the database. I can do this in the controller before it returns or in an ActionFilterAttribute. I want to be able to fire off a call to update the database, BUT I don't want to wait for completion. I want the response to return to the user without waiting for the update.
I was thinking about using a BackgroundWorker and passing in the objects.
Anyone have thoughts on if this is the good way to do this?
I think the question you should ask yourself is how much latency the database update can add to your overall response time. In most cases, it will be a lot simple to do the update as part of the request processing. Background worker is generally not a good solution but here is a good read related to that topic. If you absolutely need to do the database update outside of request processing, it will be better to consider a queueing mechanism like MSMQ, RabbitMQ, etc from the perspective of reliability.
I believe my performance problem is related to running in VS2012 debugger. When running the site directly, performance increased drastically. So I won't need to do any 'tuning tricks' if this proves out when deployed to test server.
Have you tried exploring NLog's async capabilities? We use NLog's async wrappers by wrapping a database logging target like so:
<targets async="true">
<target name="dbLog" xsi:type="Database" dbProvider="sqlserver" connectionString=".." />
.
.
</targets>
A quick startup on logging to MS SQL DB using NLog is found here
Moreover, you could make your logging method call async (.NET 4.5 required) and if you do not care for the result, choose not to await the method execution.
Look at this SO Thread for a sample NLog.config.

Is event based model used in node the same as the event based model used in C# applications?

I've heard about node.js and event based programming and things like the node event loop. In college I remember that I made an ASP.net web application. The professor said that ASP.net uses an event based architecture where callback functions on the server side were triggered by different events on the client side.
Are the two different technologies using the concept for events and event driven programming?
They're similar in that they're both using the idea of events - something that calls your code, rather than you going out and looking for changes. But in practice they're quite different.
In node (and in asp.net MVC) the events in question from the client are "this URL was requested". That's it. There's no more granularity other than the contents of the request.
In ASP.NET Webforms, they work very hard to synthesize events based on what happened on the client page. The events you get are "text changed", "button clicked", "checkbox checked"... basically the same kind of stuff you'd get in a straight desktop app.
It turns out that the Webforms model gets really, really complicated really fast, and the abstraction layer gets in the way of doing things like ajax calls.
Another thing node does is that just about everything is async events, unlike ASP.NET. Database call? Async in node, sync in ASP.NET. Read a file? Async in node, sync in ASP.NET. HTTP request to another server? You get the idea.
ASP.NET can do those things async, but you have to go out of your way to do it, and it uses threads. In node the async stuff is pretty natural and it doesn't need to use threads, resulting (somewhat surprisingly) in higher throughput in some cases.
So yes, they're the same in the sense that they're both "events", but the details are staggeringly different.
Yes, node uses an event based architecture where callback functions on the server side are triggered by different events on the client side.
Why Node.js is a big deal.
1) Using the same language on the client and the server speeds development.
2) Every web developer already knows JavaScript. The transition path to using it on the server has a lower learning curve.
3) Modules built for Node.js are all event driven. Writing event driven code on other platforms usually requires you to sift through third party modules to find the ones that are event driven. For example, there are several event driven libraries for Python, but most third party networking libraries for Python are synchronous because of Python's heritage. Same with Ruby, Java, Scala and many other platforms.
4) Speed. Node.js runs on the V8 javascript engine. It may not be quite as fast as Java or C#, but it's light years ahead of Python, Ruby and PHP. Python, Ruby and PHP make up a huge portion of the web application market share. When developers with their primary experience based in those languages need more speed, Node.js is a logical place to find it.

ASP.Net multithreaded web service calls

I have the following scenario:
We have an ASP.Net website, which generates a PDF report. To generate the PDF report we need to make multiple web-service calls (each call returns a part of the data). Most of the calls are to the same endpoint, but the methods and the parameters are different. To improve performance, we have thought of the following 2 approaches:
Expose a web service operation that accepts parameters for all the individual calls. Internally, this method calls each of the methods one by one; when completed, it packs all the responses in a collection and sends it back. The ASP.Net web page then receives the list of responses and unpacks them and generates the report.
Make parallel calls to the web service methods from the ASP.Net application. When all parallel calls are completed, collect all the responses and generate the PDF.
At first, the 2nd approach looks elegant; the problem is, how do we make the parallel web service calls. Thread.QueueUserWorkItem is not a good option as suggested here:
Using ThreadPool.QueueUserWorkItem in ASP.NET in a high traffic scenario and
http://williablog.net/williablog/category/Scalability.aspx
Creating new threads using new Thread() is also not great as suggested here:
http://blogs.msdn.com/b/tmarq/archive/2010/04/14/performing-asynchronous-work-or-tasks-in-asp-net-applications.aspx
Further, the web apps code is layered with a UI and a Business Logic Layer that invokes the web service methods. The site is not a very heavy load site, with about 200 concurrent users.
Request to help with suggestions to improve the performance of the pdf generation process.
Thanks and Regards
Vikas
Take a look at Asynchronous Pages in ASP.NET In essence it will allow you to do what you suggest in option #2 but with mechanisms that are built into ASP.NET rather than having to tap into lower level threading techniques.
see this link , its for deference of parallel programing(kind of multithreding solution) and async programing. (use Parallel programming for CPU Intensive solutions. use Asynchronous programming for IO Bound solutions.)
if you want to use threading you can use parallel.foreach or this model :
foreach (var item in Clients)
{
Tasks.Add(Task.Run(() =>
{
Result.AddRange(item.GetPoint(MasterLogId, mobileNumber));
}
}
but , asyn programing it's good solution for call web services (for many requests), becuse calling web service is i/o bound! if you use threading ,you run many threads that all of them are waiting to call(pending io).
and finally ,see my same problem and best answers .

Silverlight,asynchronous,lazy loading what's the best way?

I started to use silverlight/flex and immediately bumped into the asynchronous service calling. I'm used to solving the data access problems in an OO-way with one server fetch mechanism or another.
I have the following trivial code example:
public double ComputeOrderTotal(Order order)
{
double total = 0;
// OrderLines are lazy loaded
foreach (Orderline line in order.Orderlines)
{
// Article,customer are lazy loaded
total = total + line.Article.Price - order.Customer.discount;
}
return total;
}
If I understand correctly, this code is impossible in Flex/Silverlight. The lazy loading forces you to work with callbacks. IMO the simple expample above will be a BIG mess.
Can anyone give me a structured way to implement the above ?
Edit:
The problem is the same for Flex/Silverlight, pseudo code would
do fine
Its not really ORM related but most orms use lazy loading so i'll remove
that tag
The problem is lazy loading in the model
The above example would be very doable of all data was in memory but
we assume some has to be fetched from
the server
Closueres dont help since sometimes data is already loaded and no asynchronous fetch is needed
Yes I must agree that O/R mapping is usually done on the server-side of your application.
In SilverLight asynchronous way of execution is the desired pattern to use when working with services. Why services? Because as I said before there is no O/R mapping tool at the moment that could be used on the client-side (SilverLight). The best approach is to have your O/R mapped data exposed by a service that can be consumed by a SilverLight application. The best way at the moment is to use Ado.Net DataServices to transport the data, and on the client-side to manage the data using LINQ to Services. What is really interesting about ADS (former Astoria project) is that it is designed to be used with Entity Framework, but the good folks also implemented support for IQueriable so basically you can hook up any data provider that support LINQ. To name few you can consider Linq To Sql, Telerik OpenAccess, LLBLGen, etc. To push the updates back to the server the data source is required to support the ADS IUpdateable.
You can look just exactly how this could be done in a series of blogposts that I have prepared here: Getting Started with ADO.NET Data Services and Telerik Open Access
I can't speak to Silverlight but Flex is a web browser client technology and does not have any database driver embedded in the Flash runtime. You can do HTTP protocol interactions to a web server instead. It is there in the middle-tier web server where you will do any ORM with respect to a database connection, such as Java JDBC. Hibernate ORM and iBATIS are two popular choices in the Java middle-tier space.
Also, because of this:
Fallacies of Distributed Computing
You do not do synchronous interactions from a Flex client to its middle-tier services. Synchronous network operations have become verboten these days and are the hallmark signature of a poorly designed application - as due to reasons enumerated at the above link, the app can (and often will) exhibit a very bad user experience.
You instead make async calls to retrieve data, load the data into your client app's model object(s), and proceed to implement operations on the model. With Flex and BlazeDS you can also have the middle-tier push data to the client and update the client's model objects asynchronously. (Data binding is one way to respond to data being updated in an event driven manner.)
All this probably seems very far afield from the nature of inquiry in your posting - but your posting indicates you're off on an entirely incorrect footing as to how to understand client-side technologies that have asynchronous and event-driven programming baked into their fundamental architecture. These RIA client technologies are designed this way completely on purpose. So you will need to learn their mode of thinking if you want to have a good and productive experience using them.
I go into this in more detail, and with a Flex perspective, in this article:
Flex Async I/O vs Java and C# Explicit Threading
In my direct experience with Flex, I think this discussion is getting too complicated.
Your conceptual OO view is no different between sync and asynch. The only difference is that you use event handlers to deal with the host conversation in the DAL, rather than something returned from a method call. And that often happens entirely on the host side, and has nothing to do with Flex or Silverlight. (If you are using AIR for a workstation app, then it might be in client code, but the same applies. As well if you are using prolonged AJAX. Silverlight, of course, has no AIR equivalent.)
I've been able to design everything I need without any other changes required to accomodate asynch.
Flex has a single-threaded model. If you make a synchronous call to the web server, you'd block the entire GUI of the application. The user would have a frozen application until the call completes (or times out on a network error condition, etc.).
Of course real RIA programs aren't written that way. Their GUI remains accessible and responsive to the user via use of async calls. It also makes it possible to have real progress indicators that offer cancel buttons and such if the nature of the interaction warrants such.
Old, bad user experience web 1.0 applications exhibited the synchronous behaviour in their interactions with the web tier.
As my linked article points out, the async single-threaded model coupled with ActionScript3 closures is a good thing because it's a much simpler programming model than the alternative - writing multi-thread apps. Multi-threading was the approach of writing client-server Java Swing or C# .NET WinForm applications in order to achieve a similarly responsive, fluid-at-all-times user experience in the GUI.
Here's another article that delves into this whole subject matter of asynchronous, messaging/event-driven distributed app architecture:
Building Effective Enterprise Distributed Software Systems
data-driven communication vs behavior-driven communication
Silverlight is a client technology and the Object - Relational mapping happens completely in the server. So you have to forgot about the ORM in Silverlight.
Following your example what you have to do is to create a webservice (SOAP, REST...) that can give your silverlight client the complete "Order" object.
Once you have the object you can work with it with no communication with the server in a normal - synchronous way.
Speaking about Silverlight, you should definitely check RIA services.
Simply, it brings the DataContext from the server to the client from where you can asynchronously query it (there is no need to write WCF services by hand, it's all done by RIA).
C# 5
async / await construct will almost exactly what I want..
watch presentation by anders hejlsberg

Resources