有人可以帮我这个 - 在下面的代码中,选项3适用于我,但这是一个SYNC调用,选项4永远不会返回哪个是真的ASYNC,我需要选项4才能工作(主要区别是使用AWAIT语法)。
//来自MVC APP中的控制器的代码
IRBVer01AdminSite.Data.ApiClient apic = new Data.ApiClient();
IRBVer01AdminSite.Models.Producer prd = new IRBVer01AdminSite.Models.Producer();
// opt 3 - Make a HTTP call to API DLL - BUT this one is Syncronous
source = null;
source = apic.RunAsync("http://localhost:56099/", string.Concat("api/producers/", id.ToString().Trim())).Result;
producer = null;
destination = null;
destination = Mapper.Map<IRBVer01CodeFirst.IRBVer01Domain.Producer>(source);
producer = destination;
if (producer == null)
return HttpNotFound();
//
// opt 4 - Make Http call to API DLL - Syncronous method (FAILS SO FAR)
source = null;
source = apic.GetAsyncData("http://localhost:56099/", string.Concat("api/producers/", id.ToString().Trim())).Result;
producer = null;
destination = null;
destination = Mapper.Map<IRBVer01CodeFirst.IRBVer01Domain.Producer>(source);
producer = destination;
if (producer == null)
return HttpNotFound();
//
// MVC APP中的ApiClient CLASS代码
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;
// called on OPT 3
public async Task<IRBVer01Api.Models.Producer> RunAsync(string urlBase, string urlPath)
{
IRBVer01Api.Models.Producer producer = null;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(urlBase);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetStringAsync(urlPath).Result; // No.1 - This is not SYNC, there is no AWAIT syntax used
producer = Task.Factory.StartNew(() => JsonConvert.DeserializeObject<IRBVer01Api.Models.Producer>(response)).Result;
}
return producer;
}
// called on OPT 4
public async Task<IRBVer01Api.Models.Producer> GetAsyncData(string urlBase, string urlPath)
{
IRBVer01Api.Models.Producer producer = null;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(urlBase);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetStringAsync(urlPath); // No.1 - This is ASYNC Version but comipler never comes back
//No.1 - for a moment forget about whats happening on the next syntax, the last line is not coming back... EVER
//producer = Task.Factory.StartNew(() => JsonConvert.DeserializeObject<IRBVer01Api.Models.Producer>(response)).Result;
}
return producer;
}