How to call async method from sync in C#? - c#

I am adding a new web API call to existing functionality. I want to make this API call async but looks like it is causing deadlock. I have to make a lot more changes if I want to make entire code channel async which is not possible.
Questions I have are:
Is it possible to call async method from regular method?
What am I missing here? OR What is the correct approach here?
Code:
// Exisitng Method
public Tuple<RestaurantDeliveryProvider, DeliveryHubResult, Task<DeliveryManagerQuoteResponse>> CreateDeliveryRequest(OrderContextDTO orderContextDto)
{
var provider = RestaurantBl.GetDeliveryProviderInformationByRestaurantId(orderContextDto.RestaurantId ?? 0);
var deliveryHubResult = RestaurantBl.GetDeliveryHubResult(orderContextDto.OrderId ?? 0);;
// New Call which always comes back with "Not Yet Computed" result
Task<DeliveryManagerQuoteResponse> deliveryManagerQuoteResponse = _deliveryManager.CreateQuoteRequestAsync(orderContextDto, orderInfo);
return Tuple.Create(provider, deliveryHubResult, deliveryManagerQuoteResponse);
}
Async Methods:
public async Task<DeliveryManagerQuoteResponse> CreateQuoteRequestAsync(OrderContextDTO orderContextDto, OrderInfoDTO orderInfo)
{
DeliveryManagerQuoteResponse deliveryManagerQuoteResponse = null;
try
{
var restaurantInfo = RestaurantApi.GetRestaurant(orderInfo.RestaurantId);
var quoteRequest = new DeliveryManagerQuoteRequest
{
DeliveryProvider = null,
Country = orderContextDto.DeliveryEstimateRequestDto.RequestedDeliveryAddress.Country,
Concept = "BK",
StoreName = "BK-TEST-US-4",
OrderId = orderInfo.OrderId.ToString(),
AllowCash = false,
PaymentType = OrderPaymentType.Prepaid_Credit,
Note = orderInfo.DeliveryInstructions,
};
deliveryManagerQuoteResponse = await Quote(quoteRequest);
}
catch (Exception ex)
{
Log.ErrorFormat("Get Delivery Manager Quote failed: Error: {0}, OrderId: {1}", ex.Message, orderContextDto.OrderId);
}
return deliveryManagerQuoteResponse;
}
public async Task<DeliveryManagerQuoteResponse> Quote(DeliveryManagerQuoteRequest quoteRequest)
{
DeliveryManagerQuoteResponse deliveryManagerQuoteResponse;
var client = HttpClientFactory.GetClient();
var content = HttpClientFactory.JsonContentFactory.CreateJsonContent(quoteRequest);
var response = await client.PostAsync("https://myUrl", content);
if (response.IsSuccessStatusCode)
{
var data = await response.Content.ReadAsStringAsync();
deliveryManagerQuoteResponse = JsonConvert.DeserializeObject<DeliveryManagerQuoteResponse>(data);
}
else
{
throw new Exception((int)response.StatusCode + "-" + response.StatusCode);
}
return deliveryManagerQuoteResponse;
}
I tried following as well but same result:
public async Task<DeliveryManagerQuoteResponse> Quote(DeliveryManagerQuoteRequest quoteRequest)
{
DeliveryManagerQuoteResponse deliveryManagerQuoteResponse;
using (var client = new HttpClient())
{
var content = HttpClientFactory.JsonContentFactory.CreateJsonContent(quoteRequest);
var response = await client.PostAsync("https://myUrl", content);
if (response.IsSuccessStatusCode)
{
var data = await response.Content.ReadAsStringAsync();
deliveryManagerQuoteResponse = JsonConvert.DeserializeObject<DeliveryManagerQuoteResponse>(data);
}
else
{
throw new Exception((int)response.StatusCode + "-" + response.StatusCode);
}
}
return deliveryManagerQuoteResponse;
}
Output (sorry for the blurry output, if you click on it, you will see clear result):

don't
don't
Basically, there is no good or workable way to call an async method from a sync method and wait for the answer. There's "sync over async", but that's an anti-pattern and should be aggressively avoided.
So either:
rewrite the caller to be async
implement a synchronous version of the API

Related

How to await for an PostAsync method in xamarin?

I am trying to do something like await client.PostAsync() in a xamarin project, but it does not waits. How can I make it wait ? The same code in winforms project does waits.
my code
private bool ConfirmLogin(string user, string password)
{
bool result = false;
AppLoginRequest appLoginRequest = new AppLoginRequest();
AppLoginResponse appLoginResponse = new AppLoginResponse();
// step 1
Task<HttpResponseMessage> task = GetAppLogin(appLoginRequest, appLoginResponse);
// step 4
result = appLoginResponse.Authorized;
return result;
}
and the code for GetAppLogin
private async Task<HttpResponseMessage> GetAppLogin(AppLoginRequest appLoginRequest, AppLoginResponse appLoginResponse)
{
HttpResponseMessage response = null;
string JsonData = JsonConvert.SerializeObject(appLoginRequest);
System.Net.Http.StringContent restContent = new StringContent(JsonData, Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
try
{
// step 2
response = await client.PostAsync(#"http://x.x.x.x:xxxx/api/XXX/GetAppLogin", restContent);
// step 3
if (response.IsSuccessStatusCode)
{
var stream = await response.Content.ReadAsStringAsync();
AppLoginResponse Result = JsonConvert.DeserializeObject<AppLoginResponse>(stream);
}
else
{
appLoginResponse.Remark = response.ReasonPhrase;
}
}
catch (Exception ex)
{
appLoginResponse.Authorized = false;
appLoginResponse.Remark = ex.Message;
}
return response;
}
What I need is to execute the steps (// step x in the comments of the code) in the correct sequential order.
Step 1, then step 2, then step 3 and finally step 4
But it executes like this
step 1 then step 2 and then step 4 and step 3
This off course messes up the complete logic, is there a way I can force the client.PostAsync to actually really wait ?
I found hundreds of questions on how to run an async task synchronously, but all seem to not work.
Is xamarin different about this ?
I run the exact same code from a testclient written in winforms and there it does waits.
async void ButtonClick(...)
{
bool x = await ConfirmLogin(..., ...);
}
private async Task<bool> ConfirmLogin(string user, string password)
{
bool result = false;
AppLoginRequest appLoginRequest = new AppLoginRequest();
AppLoginResponse appLoginResponse = new AppLoginResponse();
// step 1
await GetAppLogin(appLoginRequest, appLoginResponse);
// step 4
result = appLoginResponse.Authorized;
return result;
}
Do not use async void when you can avoid it. It is a cop-out especially intended for eventhandlers. "To get the async going"

This OperationContextScope is being disposed out of order

I am calling WCF service in ASP.NET Core and everything is working fine, but whenever end of using gets executed, I get an error:
This OperationContextScope is being disposed out of order
I believe I am using wrong pattern to call WCF service using async/await but I am not sure what I am doing wrong.
Below is the code I am using to call a service.
[HttpPost]
public async Task<IActionResult> Runcase(IFormCollection formCollection)
{
if (ModelState.IsValid)
{
var runnumber = formCollection["Run number"];
await CallServiceasync();
return RedirectToAction("", "");
}
else
{
return View(formCollection);
}
}
public async Task CallServiceasync()
{
var product = p1.Value;
var a = product.first;
foreach (int Age in a.age)
{
foreach (int Gender in a.sex)
{
foreach (int Healthclass in a.uclass)
{
RequestData requestData = new RequestData()
{
ProductID = 534,
STATE = "CO",
AGE1 = Age,
SEX1 = Gender,
UND_CLASS1 = Healthclass,
};
RecieveResponseasync(requestData);
}
}
}
}
public async Task RecieveResponseasync(InputValues inputValues)
{
string reqedata = "";
string apikey = "001010iZno7001010L";
QuoteEngineService.MarketingSoftwareClient Service = new QuoteEngineService.MarketingSoftwareClient();
await Service.OpenAsync();
try
{
using (OperationContextScope scope = new OperationContextScope(Service.InnerChannel))
{
HttpRequestMessageProperty httpRequestMessage = new HttpRequestMessageProperty();
httpRequestMessage.Headers.Add("apikey", apikey);
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestMessage;
reqedata = inputValues.XmlSerializetoString();
var result = await Service.ProcessRequestAsync(reqedata, "4fa2-ae27");
var outputvalues = new OutputvaluesViewModel();
outputvalues = result.DeserializeToObject();
List<OutputValue> outputs = new List<OutputValue>();
if (outputvalues.InitialPremium != null)
outputs.Add(new OutputValue { Name = "InitialPremium", Result = outputvalues.InitialPremium});
if (outputvalues.TargetPremium != null)
outputs.Add(new OutputValue { Name = "TargetPremium", Result = outputvalues.TargetPremium });
foreach (var output in outputs)
{
await _context.outputValues.AddAsync(output);
await _context.SaveChangesAsync();
}
await Task.Delay(500);
}
}// **At this point I am getting error**
catch (Exception ex)
{
throw;
}
finally
{
if (Service.State == System.ServiceModel.CommunicationState.Opened)
{
await Service.CloseAsync();
}
}
}
From the docs:
Warning
Do not use the asynchronous "await" pattern within a OperationContextScope block. When the continuation occurs, it may run on a different thread and OperationContextScope is thread specific. If you need to call "await" for an async call, use it outside of the OperationContextScope block.

Making parallel api calls and handling each response asynchronously in c#

I have a scenario where I need to make multiple api calls (same api with different parameters) parallely in c# (Xamarin iOS and Xamarin Android). And I don't want to wait for all tasks to complete, instead whenever a response comes I should process it and update the UI accordingly.
Method that needs to be called multiple times
public async Task<Response> GetProductsAsync(int categoryId, int pageNo = -1, int pageSize = -1)
{
try
{
string url = "";
if (pageNo == -1 || pageSize == -1)
url = $"catalog/v1/categories/{categoryId}/products";
else
url = $"catalog/v1/categories/{categoryId}/products?page-number={pageNo}&page-size={pageSize}";
var response = await client.GetAsync(url);
string responseString = await response.Content.ReadAsStringAsync();
GetParsedData(response.IsSuccessStatusCode, responseString);
}
catch (Exception e)
{
apiResponse.status = "internalError";
apiResponse.data = e.Message;
}
return apiResponse;
}
From calling function you may write the code as below
public void CallingFunctionToGetProductsAsync() {
Task.Run(async () =>
{
var response = await GetProductsAsync(1);
ProcessResponse(response);
});
Task.Run(async () =>
{
var response = await GetProductsAsync(2);
ProcessResponse(response);
});
}
This is how you can wait for multiple tasks asynchron and update the UI whenever any of them completes.
async Task GetSomeProductsAsync( IEnumerable<int> categoryIds )
{
List<Task<Response>> tasks = categoryIds
.Select( catId => GetProductsAsync( catId ) )
.ToList();
while ( tasks.Any() )
{
var completed = await Task.WhenAny( tasks );
tasks.Remove( completed );
var response = completed.Result;
// update the ui from this response
}
}
As a side note:
You should add ConfigureAwait(false) to your awaiting code in GetProducsAsync to avoid uneccessary sync with the caller thread (wich would be the UI here)
public async Task<Response> GetProductsAsync(int categoryId, int pageNo = -1, int pageSize = -1)
{
try
{
string url = "";
if (pageNo == -1 || pageSize == -1)
url = $"catalog/v1/categories/{categoryId}/products";
else
url = $"catalog/v1/categories/{categoryId}/products?page-number={pageNo}&page-size={pageSize}";
var response = await client.GetAsync(url).ConfigureAwait(false);
string responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
GetParsedData(response.IsSuccessStatusCode, responseString);
}
catch (Exception e)
{
apiResponse.status = "internalError";
apiResponse.data = e.Message;
}
return apiResponse;
}
You can read more about it in Stephen Cleary's blog article: Don't block on Async Code

using data on the view from async method

I'm using the geolocator plugin to retrieve my current location and add a pin to the page. Here is the service for this:
tasks.cs
public async Task<Plugin.Geolocator.Abstractions.Position> GetDeviceCurrentLocation()
{
try
{
var locator = Plugin.Geolocator.CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(1));
if (position != null)
{
return position;
}
}
catch (Exception ex)
{
Debug.WriteLine("Unable to get location, may need to increase timeout: " + ex);
}
return new Plugin.Geolocator.Abstractions.Position();
}
I'm trying to use it in the view like this :
public MapPage(List<Models.xxx> xxx, Models.yyy yyy )
{
InitializeComponent();
Tasks ts = new Tasks();
var myLocation = ts.GetDeviceCurrentLocation();
var latitudeIm = myLocation.Result.Latitude;
var longitudeIm = myLocation.Result.Longitude;
var pin1 = new Pin
{
Type = PinType.Place,
Position = new Position(latitudeIm, longitudeIm),
Title = "My Location"
};
customMap.Pins.Add(pin1);
}
My application breaks when I try this code var latitudeIm = myLocation.Result.Latitude;
I guess since I have a async task the result must be awaited. Any idea how can I use the public async Task<Plugin.Geolocator.Abstractions.Position> GetDeviceCurrentLocation() data in my view?
You should use await for async method;
var myLocation = await ts.GetDeviceCurrentLocation();
var latitudeIm = myLocation.Latitude;
var longitudeIm = myLocation.Longitude;
You should decorate all methods as async completely. If you don't able to apply it (I wouldn't recommend it), you could use ConfigureAwait to prevent deadlock;
var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(1)).ConfigureAwait(false);
var myLocation = ts.GetDeviceCurrentLocation().Result;//Also don't hit the Result twice
var latitudeIm = myLocation.Latitude;
var longitudeIm = myLocation.Longitude;

Returning Void in Async method from WEB API Controller

I have this async method inside ASP.NET MVC 4 WEB API Controller that I got from this blog:
http://www.strathweb.com/2012/04/html5-drag-and-drop-asynchronous-multi-file-upload-with-asp-net-webapi/
public async Task<IList<RecivedFile>> Post()
{
List<RecivedFile> result = new List<RecivedFile>();
if (Request.Content.IsMimeMultipartContent())
{
try
{
MultipartFormDataStreamProvider stream = new MultipartFormDataStreamProvider(HostingEnvironment.MapPath("~/USER-UPLOADS"));
IEnumerable<HttpContent> bodyparts = await Request.Content.ReadAsMultipartAsync(stream);
IDictionary<string, string> bodyPartFiles = stream.BodyPartFileNames;
IList<string> newFiles = new List<string>();
foreach (var item in bodyPartFiles)
{
var newName = string.Empty;
var file = new FileInfo(item.Value);
if (item.Key.Contains("\""))
newName = Path.Combine(file.Directory.ToString(), item.Key.Substring(1, item.Key.Length - 2));
else
newName = Path.Combine(file.Directory.ToString(), item.Key);
File.Move(file.FullName, newName);
newFiles.Add(newName);
}
var uploadedFiles = newFiles.Select(i =>
{
var fi = new FileInfo(i);
return new RecivedFile(fi.Name, fi.FullName, fi.Length);
}).ToList();
result.AddRange(uploadedFiles);
}
catch (Exception e)
{
}
}
return result;
}
My question is why exactly does this method have a return type of Task? It is not clear "where to" or "to whom" it returns this task? It's like there is no one that waits for/receives the returned object.
I wonder what will be the implications if I return void like this:
EDIT:
I have tried the code below and it completely breaks the program. it's like the runtime looses the reference to the code, the code itself doesn't finish running.
public async void Post()
{
List<RecivedFile> result = new List<RecivedFile>();
if (Request.Content.IsMimeMultipartContent())
{
try
{
MultipartFormDataStreamProvider stream = new MultipartFormDataStreamProvider(HostingEnvironment.MapPath("~/USER-UPLOADS"));
IEnumerable<HttpContent> bodyparts = await Request.Content.ReadAsMultipartAsync(stream);
IDictionary<string, string> bodyPartFiles = stream.BodyPartFileNames;
IList<string> newFiles = new List<string>();
foreach (var item in bodyPartFiles)
{
var newName = string.Empty;
var file = new FileInfo(item.Value);
if (item.Key.Contains("\""))
newName = Path.Combine(file.Directory.ToString(), item.Key.Substring(1, item.Key.Length - 2));
else
newName = Path.Combine(file.Directory.ToString(), item.Key);
File.Move(file.FullName, newName);
newFiles.Add(newName);
}
}
catch (Exception e)
{
}
}
}
The ASP.NET runtime waits for it. You may find this video useful.
Most examples for async assume a UI context. ASP.NET also provides a context, but it's a "request" context - one for each HTTP request. My async/await post gives an overview of this "context", and the async/await FAQ goes into much more detail.
With return type void you don't wait for an object to return.. You wait for an operation to finish. You wait for your Task to finish.
If you return void, you will be returning 204 "No Content" Response message immediately regardless of the completion status of your asynchronous operation. This is done by the help of VoidResultConverter.
Note: On RC, you will see that it returns 200 "OK" response but with
the RTM, it will return 204 "No Content" response.

Categories

Resources