【发布时间】:2017-02-03 01:07:37
【问题描述】:
我正在尝试在 Global.asax 中执行 async/await Web API Post,以免在执行 Rest-api-post 时阻止应用程序加载。
但是应用程序永远不会启动,如果不异步执行,事情会变得更快。我在这里做错了什么?
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
protected void Session_Start(object sender, EventArgs e)
{
var somePostValue = myJsonString();
RunAsync(somePostValue).Wait();
}
private static async Task RunAsync(string postValue)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:56789/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PostAsJsonAsync("api/MyApi", postValue);
}
}
}
【问题讨论】:
-
无论如何,您只是在异步操作上同步等待,其行为与同步版本一样,但会增加设置异步操作的开销。
-
@Servy 感谢您的回复。那你在说什么?在 global.asax 中不能异步调用 api 吗?
-
我是说你实际上并没有异步执行它。
-
@Servy 好的。你能告诉我怎么做吗?
-
不要同步等待操作完成。
标签: c# asp.net asynchronous