why controller methods are processed sequentially in browser - c#

I've the following controller Home:
[HttpGet]
public void Index()
{
Response.Write($"{DateTime.Now} begin <br>");
Thread.Sleep(5000);
Response.Write($"{DateTime.Now} end <br>");
}
when i open ~/Home/Index with browser in two tabs , i see that request is processed sequentially. Session disabled. How to make browser to process request concurrently ?

I don't know why, I guess the browser may thought the requests are the same and would like to checks if the response can be cached before sending the second request.
To run it concurrently, one simple way is to append fake parameter to the url to make them different every time, for example,
/Home/Index?p=1
/Home/Index?p=2

Related

c# send more than a single request at the same time to the same page (ex: for a login )

I saw that in order to send requests at the same time to a page (for example for a login 10 POST requests and get if success or fail for each request) I have to use asynchronous requests in c#. I saw some codes about asynchronous requests but they don't send for example 10 requests at the same time and I don't understand how to do this. I also tried to get codes to do this with threads but no results reached. Can you make an example for me that can do what I described?
ApiController - example method in controller
// GET: api/currencies
[HttpGet]
[ResponseCache(Duration = 60)]
public async Task<IEnumerable<GetCurrencyResponse>> Get()
{
var currencies = await _currencyService.GetCurrenciesAsync();
return currencies;
}
Fiddler - you can catch request by using fiddler app (https://www.telerik.com/fiddler), select it from requests list, click "s", write 10 and click "Ok" button to send ten exactly the same requests.

handle multiple request of REST API

I have create a rest api using api Controller in ASP.NET and performing some task that may take 10 minutes to finish task because user enter the time to finish that task. In this case I think multiple request can't be handle.
I am using this --
public class Controller : ApiController
{
[HttpGet]
[ActionName("APICall")]
public string API()
{
Rest y = new Rest();
return y.APiDATA();
}
}
my question is during performing this task when one more request come then does it create new thread for each request or not? if not then how to handle concurrent request .
Please help me.
I am getting following error when calling url after deploy in IIS
{"Message":"An error has occurred.","ExceptionMessage":"Object reference not set to an instance of an object.","ExceptionType":"System.NullReferenceException","St‌​ackTrace":" at restapi.service.Rest.synthetic()\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.Ac‌​tionExecutor.<>c__Di‌​splayClass13.b__c(Ob‌​ject instance, Object[] methodParameters)\r\n at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult]‌​(Func`1 func, CancellationToken cancellationToken)"}
Each request that comes in will be on a separate thread (Task), but also each request that comes in will be on a new instance of your Controller class. However, you'll find that any client that doesn't get a response back within a small period of time (say 10 seconds, or maybe if you're lucky, 60 seconds), will consider it a timeout.
You probably need to park the processing somewhere else (say in a worker queue, and make sure you have a worker running that can handle it), and give back in your response a token they can use to poll for status. Or some other means of communicating to them when the job is done.
Each Web API request works its own separate thread and so multiple request will work. But you may face time out issue.
Regards
Abdul

C# Web-Api - processing inbound requests 'in order that they are recieved'

I've written a web-api project to act as a bridge/gateway between two sub-systems.
I need to ensure that inbound requests are processed 'in the order that they are received'. I'm not overaly familiar with how web-api works and the concern I have is this:
An inbound request comes in, an operation is kicked off and lasts 30 seconds.
Within 5 seconds of the first request being processed, and second request is received and is immediately also processed.
The reason for the concern is that a user may submit an update to a record which will propagate to the other sub-system. However that user may for whatever reason submit a second request. I need to ensure that the first request is completed first, before the subsequent request is actioned. So when hundres of requests are flooding in, it's just a case of processing on a first come, first served basis.
Does anyone know if web-api sort of works like this already, or what I'd need to do in order to get this behaviour?
You can do this this by using global static flag.
Declare one variable like this
static bool bInProcess = false;
Now, when you receive request set this variable to true and do your process. Once you done with your process set this variable to false; During your process if another request come then check this variable if its true then put current thread in sleep mode for 1 sec and check until its true. OR you can return error that another process is running.
//Sample for loop to Queue 2nd request
while (bInProcess )
{
Thread.Sleep(1000);
}
You have to be very careful in this code. In "WebApiConfig" class add the messagehandler class and write this code in that class. Use this method "config.MessageHandlers.Add". I did it long time ago, so I know it works.

MVC4 - Display upload progress for each file while uploading multiple files

I'm building an mvc 4 application that makes file uploading. When I get HttpPostedFileBase range, I get streams on them and pass to my business logic layer to save them and bind with database records. This is done without any problems. But when displaying current state of uploading progress comes in, I'm a bit confused. I make a second request while an uploading runs, but it waits for first request to be executed completely.
I know that in same browser client instance (actually same session), my requests are synchronized. But there is a solution that I read about, asynchronous actions.
To try asynchronous actions, I used Stream.CopyToAsync(..) instead of Stream.CopyTo(..). I'm also using Task.Delay(10000) to simulate file uploading progress. Then while asynchronous UploadFile action runs, I invoked synchronous UploadProgress on same browser instance. Result is still waiting for first request to complete. Below is the code I use. Where am I wrong?
Here is async action to upload files;
[HttpPost]
public async Task<ActionResult> Upload(PFileUploadModel files)
{
if (!Session.GetIsLoggedIn())
return RedirectToAction("Login", "User");
var fileRequest = Session.CreateRequest<PAddFileRequest, bool>(); //Creates a business logic request
fileRequest.Files.Add(...);
var result = await Session.HandleRequestAsync(fileRequest); //Handles and executes a business logic request by checking authority
if (result)
return RedirectToAction("List");
return RedirectToError();
}
And upload progress action is simple as below for now :) :
public ActionResult UploadProgress()
{
//var saveProgressRequest = Session.CreateRequest<PSaveFileProgressInfoRequest, PSaveFileProgressInfoResponse>();
//saveProgressRequest.ProgressHandle = progressHandle;
//var response = Session.HandleRequest(saveProgressRequest);
return Content("Test!");
}
Thanks for helping.
async doesn't change the HTTP protocol. The Upload request is in progress until you return the result.
You're probably running into the ASP.NET session lock, which ensures that multiple request handlers don't interfere with each other when reading/writing session state. I believe that MVC always takes a write lock on the session state by default, preventing any other actions from executing simultaneously (in the same session).
You can override this behavior by specifying the SessionState attribute on your controller.

Threading using AJAX

When the user clicks on a link to generate report I make an AJAX call which generates a pdf file in the background.Now the files are huge running upto 10mb or more.So it takes some time.In the mean time the user should be able to navigate other links as if nothing has happened.So I need to implement in such a way that the pdf generation process gets started & user doesn't have to wait for the process to finish.Is this possible?I am using AJAX Pro with c# with dot net framework 2.0
The problem here is that as soon as the AJAX activity begins the browser enters into a hung stage & the user has to wait although he clicks on a different link.
I would probably create a 'queue' or an 'inbox' for the user ...
start your pdf generation routine with a ThreadPool.QueueUserWorkItem (you would also need to modify your generation method to output to their inbox)
then on each http request check that inbox and notify the user of the item ... you can always poll the server on an interval or somthing
Sure, but once the user navigates to another page, the Javascript that is waiting for the Ajax response is no longer running, so that request is lost. You'd have to either find a way to keep that page open (using frames or exclusively Ajaxified navigiation), or find a way to store the response and notify the user of its completion on the next page view. For instance, storing a session variable that indicates that the operation is completed, or storing it in a database with (perhaps) an "unread" boolean value.
You can have asynchronous Ajax call with which you can do other tasks while response objects returns from the Ajax page.
Here is some example, testAjax.aspx is the Ajax page here :
http_request.onreadystatechange = function() { alertContents(http_request); };
http_request.open('GET', 'testAjax.aspx?', true);
http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
http_request.send(null);
function alertContents(http_request)
{//debugger;
if (http_request.readyState == 4)
{
if (http_request.status == 200)
{
var vResult;
vResult=http_request.responseText;
//Write your logic after successful Ajax call here.
}
else
{
alert('There was a problem with the request.');
}
}
}

Categories

Resources