我已經使用了一些異步編碼,但我並沒有真正理解如何使用它 - 雖然我理解了這個概念以及爲什麼需要它。想了解異步
這裏是我的設立:
我有一個Web API,我會從我的ASP.NET MVC應用程序,我的Web API將調用DocumentDB調用。在代碼示例中,我向DocumentDB發送查詢時看到很多await關鍵字。
我很困惑,如果我需要在我的MVC應用程序異步中使我的索引操作方法? 我也很困惑,如果我的Web API中的CreateEmployee()方法應該是異步的?
在這種情況下使用異步的正確方法是什麼?
這裏是我的代碼(此代碼是目前給我的錯誤,因爲我的MVC操作方法是不是異步) ---- ASP.NET MVC應用程序代碼----
public ActionResult Index()
{
Employee emp = new Employee();
emp.FirstName = "John";
emp.LastName = "Doe";
emp.Gender = "M";
emp.Ssn = "123-45-6789";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://myWebApi.com");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.PostAsJsonAsync("hr/create/newemployee", emp);
if (response.IsSuccessStatusCode)
{
emp = await response.Content.ReadAsAsync<Employee>();
}
}
// Display employee info
return View(emp);
}
----網絡API代碼----
private static readonly string endPointUrl = ConfigurationManager.AppSettings["EndPointUrl"];
private static readonly string authorizationKey = ConfigurationManager.AppSettings["AuthorizationKey"];
private static readonly string databaseId = ConfigurationManager.AppSettings["DatabaseId"];
private static DocumentClient client;
public static async Task<Employee> CreateEmployee(Employee emp)
{
try
{
//Create a Document client
using (client = new DocumentClient(new Uri(endPointUrl), authorizationKey))
{
//Get the database
var database = await GetDatabaseAsync();
//Get the Document Collection
var collection = await GetCollectionAsync(database.SelfLink, "Employees");
await client.CreateDocumentAsync(collection.SelfLink, emp);
// Further process employee
}
}
catch
{
// Handle error
}
return employee;
}
private static async Task<DocumentCollection> GetCollectionAsync(string dbLink, string id)
{
DocumentCollection collection = client.CreateDocumentCollectionQuery(dbLink).Where(c => c.Id == id).ToArray().FirstOrDefault();
return collection;
}
private static async Task<Database> GetDatabaseAsync()
{
Database database = client.CreateDatabaseQuery().Where(db => db.Id == databaseId).ToArray().FirstOrDefault();
return database;
}
在你的情況下,當你說等待時你可以釋放一些資源。但是,可以使用tasks.whenall來改進 - 請閱讀以下內容:http://msdn.microsoft.com/en-AU/library/hh556530.aspx – codebased 2014-11-25 00:38:31