Ho usato un po 'la codifica asincrona, ma non capisco davvero come usarlo, anche se capisco il concetto e perché ne ho bisogno.Vuoi capire async
Ecco il mio set up:
Ho un API Web che chiamerò dalla mia applicazione ASP.NET MVC e il mio Web API chiamerà DocumentDB. Negli esempi di codice, vedo molte parole chiave attese durante l'invio di query a DocumentDB.
Sono confuso se devo rendere il mio metodo di azione Indice nella mia app MVC asincrona? Sono confuso anche se il mio metodo CreateEmployee() nella mia API Web dovrebbe essere asincrono?
Qual è il modo corretto di utilizzare async in questo scenario?
Ecco il mio codice (Questo codice è attualmente mi dà errori perché il mio metodo di azione MVC non è asincrona) ---- ASP.NET MVC Codice 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);
}
---- Web API Codice ----
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;
}
Nel tuo caso, stai liberando alcune risorse quando dici attendi. Tuttavia, puoi migliorare utilizzando tasks.whenall - leggi questo: http://msdn.microsoft.com/en-AU/library/hh556530.aspx – codebased