Total Async in Web Applications for ASP.NET 3.5 - asp.net

I've been informing myself about the async capabilities of .net 3.5
Ive found a very good article on this : http://msdn.microsoft.com/en-us/magazine/cc163725.aspx
Now, the thing is, all these methods still require the async tasks to be finished BEFORE the Page_Render event, so in practice, the web application will still appear to be 'hanging' for the user.
My question: How can I async launch a heavy task from my aspx page, without having to wait or callback for this task when its finished, and then just render the page. The actual work is being done in a WCF service ( creating document, sending mail )
Pseudo code:
void btn_Click()
{
AsyncCallWcfServiceButDontWaitForIt();
lblFeedback.Text = "Your documents are beging generated and mailed in the background";
}
I'd like to give the user direct feedback while the rest is being handled in the background. I've implemented something like this with executing a console script but I'm looking for a possible better async way.
Please also note I'm looking for a .NET 3.5 solution!
Thanks in advance

What you are looking for is not async here (though you should also be doing that)... what you are looking for is AJAX; you render the page, then load the slow-loading information via Ajax (with async code, just as usual)

Related

How to add UserManagerExtension class methods in Asp.Net Core 2.0?

I am migrating my current project to core, and in my current project I have many synchronous method calls from UserManagerExtension class like Create, FindById, AddToRole etc. But despite thorough searching online I am not able to find the same in core.
Is it deprecated in core 2.0? If not, what is the namespace and how to include it?
As far as I can tell, they are gone. However, their existence was suspect even before. All the extensions did was simply run the async versions "synchronously", which basically means they spun off a task that blocked on the async call until it completed. While this technically satisfies having a "synchronous" method, it's actually really bad for web applications as you're sacrificing threads from your pool to do the work synchronously.
In ASP.NET MVC, it was a necessary evil, though, since there were many aspects that did not support async: child actions, action filters, etc. However, in Core, everything is async, and things happening in a web application space should be async. Therefore, there's simply no good reason to ever use sync methods, so that's probably why they no longer exist.
If you still need to run the async methods as sync, for some reason, you can simply block on them yourself:
var user = UserManager.FindByIdAsync(id).GetAwaiter().GetResult();
Be aware, though, that can deadlock in certain situations, because of the context shift. The two ways to avoid that are:
Use ConfigureAwait(false)
var user = UserManager.FindByIdAsync(id).ConfigureAwait(false).GetAwaiter().GetResult();
However, you cannot use ConfigureAwait(false) in something like an action method, since the context must be maintained in order to complete the response. You can use it in a method called by the action method, though:
private ApplicationUser GetUser(string id)
{
return UserManager.FindByIdAsync(id).ConfigureAwait(false).GetAwaiter().GetResult();
}
...
var user = GetUser(id);
Run it in a different thread
Task.Run(() => {
var user = UserManager.FindByIdAsync(id).GetAwaiter().GetResult();
// code here that needs `user`
});
As you can see, with this method the work you send off must be self-contained, so it's probably not a good fit in most scenarios. Also, again, this is extremely bad for web applications.
Long and short, there's not really a good way to run async as sync, and you should avoid it as much as possible. Async should be async all the way. That did use to be an issue in MVC, but now it's not with Core.

Pattern for Asynchronous Web-api method with registered callback

I'm looking at how to create a .net web-api method which is asynchronous i.e:
- It runs the actual task as a background task but returns a status straightaway
- It is also passed callback information which it calls back when background task is complete.
I understand the theory and have noticed articles around Request/Acknowledge however im struggling to find a well document .net version of the pattern which achieves the above and doesn't cause multi-threading issues on my web-api? I don't want to do anything bespoke because surely this is a common .net implementation?
ok seems like there nothing magical in terms of solution:
public HttpResponseMessage SomePostMethod(Request request)
{
Validate(request);
QueueForBackGroundAsync(request);
return HttpStatusCode.Accepted;
}

Asynchronous event in asp.net webforms

I have the following use case:
A user can filter on my asp.net web project for some data and request the result as PDF. The PDF is generated per request new and returned to the user. I got already everything to run.
But: the processing can take up to two minutes and the user should be able to continue to use the page.
I tried to use a second tab, but both tabs are blocked. Even when I use the PageAsyncTask class and the async attribute. When I use a thread to perform the request, I am truly parallel, but I have no clue, how to interact with the user from inside the thread when the work is done.
How can I send an async request to the server and just get the result on the page, in whatever form, when its finished?
Dave Encosia does a great job explaining how you can do this:
Using jQuery to directly call ASP.NET AJAX page
methods
Using jQuery to Consume ASP.NET JSON Web
Services
3 mistakes to avoid when using jQuery with ASP.NET
AJAX

Implementing long running search in ASP.NET

I am building a search page in asp.net 3.5. Search takes a bit of time (few seconds to few minutes). Current I use AsyncMethodCaller to call Search method. AsyncMethodCaller method stores search results in Session. I user Ajax timer to check if Search method finished and then display results.
What would be the best way to implement this scenario?
I would use a Page Method from the ASP.NET Ajax Framework. It's easy to call them async and you have a callback when it's done.
Have a look here. (Async is explained at the commens of the post)
You could try the reactive extensions for .NET . I haven't tried them yet, but looks promising.
That seems perfectly fine to me, or have I missed the point of the question?
I did a similar thing recently in a PHP front-end with a search that takes about 30 seconds.
I implemented the actual search logic as a console application. The web service calls the console application to carry out the search and records the process ID of the application handling the search in the session.
An AJAX timer in the front-end polls the server every second, which checks if that process ID is still running. If it's finished, it looks in the database (where the application writes the results) and sends those back to the front-end.
If Javascript is disabled, a simple meta refresh does the same thing.

Custom Windows Workflow activity that executes an asynchronous operation - redone using generic service

I am writing a custom Windows Workflow Foundation activity, that starts some process asynchronously, and then should wake up when an async event arrives.
All the samples I’ve found (e.g. this one by Kirk Evans) involve a custom workflow service, that does most of the work, and then posts an event to the activity-created queue. The main reason for that seems to be that the only method to post an event [that works from a non-WF thread] is WorkflowInstance.EnqueueItem, and the activities don’t have access to workflow instances, so they can't post events (from non-WF thread where I receive the result of async operation).
I don't like this design, as this splits functionality into two pieces, and requires adding a service to a host when a new activity type is added. Ugly.
So I wrote the following generic service that I call from the activity’s async event handler, and that can reused by various async activities (error handling omitted):
class WorkflowEnqueuerService : WorkflowRuntimeService
{
public void EnqueueItem(Guid workflowInstanceId, IComparable queueId, object item)
{
this.Runtime.GetWorkflow(workflowInstanceId).EnqueueItem(queueId, item, null, null);
}
}
Now in the activity code, I can obtain and store a reference to this service, start my async operation, an when it completes, use this service to post an event to my queue. The benefits of this - I keep all the activity-specific code inside activity, and I don't have to add new services for each activity types.
But seeing the official and internet samples doing it will specialized non-reusable services, I would like to check if this approach is OK, or I’m creating some problems here?
There is a potential problem here with regard to workflow persistence.
If you create long running worklfows that are persisted in a database to the runtime will be able to restart these workflows are not reloaded into memory until there is some external event that reloads them. As there they are responsible for triggering the event themselves but cannot until they are reloaded. And we have a catch 22 :-(
The proper way to do this is using an external service. And while this might feel like dividing the code into two places it really isn't. The reason is that the workflow is responsible for the big picture, IE what should be done. And the runtime service is responsible for the actual implementation or how it should be done. That way you can change the how without changing the why and when part.
A followup - regardless of all the reasons, why it "should be done" using a service, this will be directly supported by .NET 4.0, which provides a clean way for an activity to start an asynchronous work, while suspending the persistence of the activity.
See
http://msdn.microsoft.com/en-us/library/system.activities.codeactivitycontext.setupasyncoperationblock(VS.100).aspx
for details.

Resources