Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Thursday, August 8, 2019 2:31 PM
I have a Thread which will call a function and the function will call Web API. I am getting - 'A task was canceled'. during httpclient.postasync method.
Can anyone help me?
Let me know anyone required code for the same.
All replies (5)
Friday, August 9, 2019 6:38 AM
Hi Sunil Gohel,
Thank you for posting here.
Could you provide some related code about httpclient.postasync method? It will help us to analyze your problem.
Besides, I have found a reference.
HttpClient - A task was cancelled?
I hope it can help you.
Best Regards,
Xingyu Zhao
MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact [email protected].
Friday, August 9, 2019 9:10 AM
Thread thread = new Thread(() => trans.PaymentTransaction(paymentTransaction, model.CALLBACK_URL, transdata.merchantUserID, transdata.transactionCode));
thread.IsBackground = true;
thread.Start();
Thread.Sleep(1);
public TransactionResponse PaymentTransaction(PaymentTransaction transaction, string callbackurl, int merchantUserID, string TransCode)
{
var task = Task.Run(async () =>
{
DMRAPILog.WriteLog("Info:\t" + DateTime.Now.ToString("MMM dd, yyyy HH:mm:ss.fff") + "\tDMR PaymentTransaction Call Bank API (Content) : " + content + Environment.NewLine, "Transaction_"+TransCode, uploads + "\Payment");
var pass = await client.PostAsync(apiurl, content);
DMRAPILog.WriteLog("Info:\t" + DateTime.Now.ToString("MMM dd, yyyy HH:mm:ss.fff") + "\tDMR PaymentTransaction Bank API Result : " + pass, "Transaction_" + TransCode, uploads + "\Payment");
if (pass.IsSuccessStatusCode)
{
var result = pass.Content.ReadAsStringAsync().Result;
DMRAPILog.WriteLog("Info:\t" + DateTime.Now.ToString("MMM dd, yyyy HH:mm:ss.fff") + "\tDMR PaymentTransaction Bank API Response : " + result, "Transaction_" + TransCode, uploads + "\Payment");
response = JsonConvert.DeserializeObject<TransactionResponse>(result);
}
});
bool isCompletedSuccessfully = task.Wait(TimeSpan.FromMilliseconds(3000));
if (isCompletedSuccessfully)
{
//return task.Result;
}
else
{
throw new TimeoutException("The function has taken longer than the maximum time allowed.");
}
}
I am getting error on below line
bool isCompletedSuccessfully = task.Wait(TimeSpan.FromMilliseconds(3000));
Error: Aug 08, 2019 18:40:59.375 One or more errors occurred. (A task was canceled.)StackTrace: at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait(TimeSpan timeout)
Friday, August 9, 2019 1:49 PM
That means somebody cancelled the request somewhere along the way. It could have happened because the remote server disconnected or because your code explicitly cancelled it. This is a possible scenario that, if you care about it, you need to handle.
var client = new HttpClient();
...
try
{
client.PostAsync(...);
} catch (AggregateException e)
{
if (e.InnerException is OperationCanceledException)
//Request was cancelled
} catch (OperationCanceledException)
{
//Request was cancelled
};
Michael Taylor http://www.michaeltaylorp3.net
Friday, August 9, 2019 2:01 PM
Sir,
Simultaneously 100 user calls ASP.Net Core Web API and 100 times new Thread instance are created and each thread will call PaymentTransaction to execute third party Web API function.
Thread thread = new Thread(() => trans.PaymentTransaction(paymentTransaction, model.CALLBACK_URL, transdata.merchantUserID, transdata.transactionCode));thread.IsBackground = true;thread.Start();Thread.Sleep(1);
The remote server received my request and executed their part, my thread got cancelled in between the third part API call. I am not getting any response from the API because my thread is cancelled.
Why the code explicitly cancelled it?
Friday, August 9, 2019 2:14 PM
No you cannot do that in a web app. Each request to a web app is called on a thread pool thread. Your app has only so long to respond to that request. If you eat up all those threads then your app is non-responsive. After a while the browser (or server) will drop the connection and your request gets cancelled.
You need to post in the ASP.NET forums how to properly make async calls in a web app. That is the issue you're running into here. You do not use threads in a web app like this. Specifically you'll create async methods that make calls to the Task API to do your work. This allows the ASP.NET runtime to continue processing other requests and (unless the browser times out your call) will allow you the time to process your request. If your request takes way too long (over 2 minutes) then you still will likely time out. You can apply attributes to your actions to extend this. However the client needs to do similar things because it has its own time.
public class MyController : Controller
{
[HttpPost]
public async Task<ActionResult> DoSomething ( CancellationToken cancellationToken )
{
await DoSomeWorkAsync(cancellationToken).ConfigureAwait(false);
//Call something not designed for async
var results = await Task.Run(() => trans.PaymentTransaction(), cancellationToken).ConfigureAwait(false);
//Return the results
return View(results);
}
}
Michael Taylor http://www.michaeltaylorp3.net