AsyncController: Interference having 2 async methods - c#

i'm having an AsyncController that has 2 AsyncMethods.
One is called GetMessages, the other Check.
It seems, that one call blocks the other, probably because both call this.AsyncManager.OutstandingOperations.Increment();
Do they share the same AsyncManager?
What is the right way to do that?
Do i have to have 2 AsyncController to ensure that they dont get in each others way?
Update:
The code of both methods is similar to code posted here: Async operation completes, but result is not send to browser
in fact, it is the same controller, only added the Check/CheckCompleted.
sometimes, the "Check" has to get triggered so that the "GetMessages" returns
Update2: I have a waittimout of 60 seconds for both methods. I reduced one now to 5, this helps it, but i think it is just a hack.

They shouldn't block. The blocking you are observing might be due to the fact that both methods use Session and because Session is not thread safe, ASP.NET blocks access if you have two parallel requests from the same session (for example AJAX requests).
So try disabling all session for those actions by decorating them with the following attribute:
[SessionState(SessionStateBehavior.Disabled)]

Related

How do I force a wait in the C# async await model

I think I must be missing something with my understanding of the async await model. What should be a simple thing seems to be unbelievably hard to achieve.
I have a UI which needs to check if the user is logged in. To do this I need to call a method in one of my classes which does some queries.
This class in turn calls 3rd party code which only has async methods.
How can I call that async method and make the application wait until I get a result?
I have tried all the things suggested such as ConfigureAwait, RunSynchronous, .Result, etc.. Nothing seems to reliably work.
It seems so stupid that something like this is so difficult so I assume I am missing a key piece of information.
Thanks.
Lets make something clear:
"make the application wait until I get a result?"
Has nothing to do (I cannot stress this enough) with blocking, awaiting or any result whatsoever.
If you are used of making the UI lock until something is done, you should switch your design, instead of trying to find a way to accomplish it.
(I have spent fair amount of time writing MFC apps for Windows Mobile, I used to do this as well)
The correct way to handle such situation, is to let the user know, that there is work being done (Some sort of Activity Indicator for example), and at the same time, make sure that no other code can be executed due to User Input (CanExecute property of your Command for example). When it is appropriate, you can put Cancelation logic.
Even more, in the context of MAUI (and mobile development in general), blocking the UI thread, even for few seconds, is totally not acceptable. It should remain responsive at all times. This is not a matter of choice.
You can use the Task.Result in the property to block the calling thread until the Task is completed. However, this is not recommended in most cases because it can lead to deadlocks. A better approach is to use await in a method marked as async, which will cause the method to return control to the calling method until the awaited Task is completed. If you need to block the thread, consider using ConfigureAwait(false) when awaiting the Task.
Read this for further information about the synchronous error handling to Async / Callback programs.

Using async method indirectly (and synchronously) in a view [duplicate]

I get the exception below when invoking he automagically generated async webmethods that i asked about in this post
Asynchronous operations are not allowed in this context. Page starting
an asynchronous operation has to have the Async attribute set to true
and an asynchronous operation can only be started on a page prior to
Google search results in add Async = True in the page directive but various people have noted that this makes the page 'Blocking' (which isn't true asynchronous operation). So how do i achieve asynchronous operation while calling webservice methods.
Check out this answer. I won't copy/paste the answers from there but I'll extend the discussion some.
The accepted answer is NOT the correct one. Since there is no 'EndInvoke' there will be a resource leak every time this method is invoked. See this discussion on why that's not okay.
What is suggested instead is to launch either a daemon thread or create whole different processes that reads from MSMQ and processes the long-running tasks there.

Session-like storage option for a non-serializable object?

Background (Skip this part if you want)
Feel free to skip over this part if you choose, it's just some background for those who want to better understand the problem
At the beginning of one action on my site, I kick off several asynchronous operations. The action returns before the operations are complete. This is what I want. However, the View that gets loaded by this action invokes several other actions in a different controller. Some of these actions rely on the results of the async calls from the first page, so I need to be able to wait on the async calls to finish from the other controller. I thought about just using Session to store the WaitHandles, but as WaitHandles aren't serializable, I obviously can't do that.
Short version:
I need to be able to store an async WaitHandle object somewhere from one controller, such that it can be reliably retrieved in a different controller. These WaitHandles also need to be user-specific, but I can handle that part. Just don't list an option that would make doing that impossible.

How do I make a .NET 4 thread wait for asynchronous requests to finish?

I am using HttpWebRequest.BeginGetRequest() to make 500 asynchronous HTTP requests from a single method. I would like that method to wait until I get a response from all the requests or they timeout.
What is the best way to do this?
I'm currently wrapping the asynchronous calls within a List of Task objects to use Tasks.WaitAll(), but I don't want to go too far down the rabbit hole before I know that this is a good solution.
Any ideas?
EDIT
I implemented counters, and they work, but I'm curious about using delegates like shown on this page.
Multi-threading and Async Examples
Has anybody done something like this before? Is it overkill?
I'm currently wrapping the asynchronous calls within a List of Task objects to use Tasks.WaitAll()
This is a fairly clean solution if you truly want to force these "tasks" to synchronize and block at this point. This is the main rationale behind Task.WaitAll(), and is nice since it (optionally) allows you to cancel the blocking operation after a timeout, if you so choose.
Personally I wouldn't block the thread, it defeats the purpose of the async model.
If I absolutely had to wait for these web requests to finish before continuing I would instead keep a counter that is incremented each time you get called back on a successful or failed request.
Check the counter on each callback and if it has hit your desired count then let the thread continue...
This way you can also keep your UI nice and responsive and perhaps update a counter/progress bar - Even if you're not kicking these off on the UI thread it's nice to provide some visual feed back tot he user about what is going on.

Is the callBack method called before the assignment or after here?

I have the code below which is basically calling a Domain Service in a SilverLight Application.
LoadOperation<tCity> loadOperation = _dataContext.Load(query,callBack, true);
Can you tell me which operation is done first?
Is the callBack method called before loadOperation variable is assigned or after it is assigned?
Thanks
Assuming it's meant to be an asynchronous operation, it could happen either way, in theory. The asynchronous operation should occur in another thread, and if that finishes before Load returns, the callback could be called before the assignment completes.
In practice, I'd expect the async call to take much longer than whatever housekeeping Load does at the end of the method - but I also wouldn't put that assumption into the code. Unless there's explicit synchronization to ensure that the assignment occurs before the callback, I don't think it's a good idea to rely on it.
Even if at the moment the assignment always happens first, consider:
What happens if there's no network connection at the moment? The async call could fail very quickly.
What happens if some caching is added client-side? The call could succeed very quickly.
I don't know what kind of testing you're able to do against the RIA services, but sometimes you may want to be able to mock asynchronous calls by making them execute the callback on the same thread - which means the callback could happen in tests before the assignment. You could avoid this by forcing a genuinely asynchronous mock call, but handling threading in tests can get hairy; sometimes it's easiest just to make everything synchronous.
EDIT: I've been thinking about this more, and trying to work out the reasons behind my gut feeling that you shouldn't make this assumption, even though it's almost always going to be fine in reality.
Relying on the order of operations is against the spirit of asynchronicity.
You should (IMO) be setting something off, and be ready for it to come back at any time. That's how you should be thinking about it. Once you start down the slippery slope of "I'm sure I'll be able to just do a little bit of work before the response is returned" you end up in a world of uncertainty.
First, I would say write your callback without any assumptions. But aside from that I don't see how the callback could possibly occur before the assignment. The load operation would have to return immediately after the thread is spun.
There are 3 possible answers to this very specific RIA Services question:
It returns the assignment before the callback.
It may be possible for the callback to occur before the assignment.
You do not care.
Case 1:
Based on a .Net Reflector investigation of the actual load method in question, it appears impossible for it to call the callback before the return occurs. (If anyone wants to argue that they are welcome to explain the intricacies of spinning up background threads).
Case 2:
Proof that "the sky is falling" is possible would have to be shown in the reflected code. (If anyone wants to support this they are also welcome to explain the intricacies of spinning up background threads).
Case 3:
In reality, the return value of a RIA Services load method is normally used to assign a lazy loading data source. It is not used by the callback. The callback is passed its own context, of the loaded data, as a parameter.
StackOverflow is all about practical code answers, so the only practical answer is option 3:
You do not care (as you do/should not use the assignment value from the callback).

Categories