Użyłem trochę kodowania asynchronicznego, ale nie do końca rozumiem, jak go używać - chociaż rozumiem koncepcję i dlaczego tego potrzebuję.Chcesz zrozumieć async
Oto mój zestaw up:
Mam Web API że wezwę z mojej aplikacji ASP.NET MVC i mojego Web API wezwie DocumentDB. W przykładach kodu widzę wiele oczekujących słów kluczowych podczas wysyłania zapytań do DocumentDB.
Jestem zdezorientowany, jeśli muszę zrobić moją metodę akcji indeksu w mojej asynchronicznej aplikacji MVC? Jestem również zdezorientowany, jeśli moja metoda CreateEmployee() w moim Web API powinna być asynchroniczna?
Jaki jest właściwy sposób korzystania z asynchronizacji w tym scenariuszu?
Oto mój kod (Kod ten jest obecnie daje mi błędy, ponieważ moja metoda działania MVC nie jest asynchroniczny) ---- ASP.NET MVC Code App ----
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);
}
---- Kod Web 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;
}
W twoim przypadku uwalniasz niektóre zasoby, gdy mówisz, że oczekujesz. Jednak można poprawić za pomocą tasks.whenall - przeczytaj to: http://msdn.microsoft.com/en-AU/library/hh556530.aspx – codebased