Ich habe Async-Codierung ein wenig verwendet, aber ich verstehe nicht wirklich, wie man es benutzt - obwohl ich das Konzept verstehe und warum ich es brauche.Willst du async verstehen
Hier ist mein Set up:
ich einen Web-API, die ich von meinem ASP.NET MVC-app und meinem Web-API DocumentDB rufen nennen. In Codebeispielen sehe ich viele abwartende Schlüsselwörter beim Senden von Abfragen an DocumentDB.
Ich bin verwirrt, wenn ich meine Indexaktionsmethode in meiner MVC-App async machen muss? Ich bin auch verwirrt, wenn meine CreateEmployee() -Methode in meiner Web-API async sein sollte?
Was ist der richtige Weg, um Async in diesem Szenario zu verwenden?
Hier ist mein Code (Dieser Code zur Zeit mir Fehler geben, weil meine MVC Aktionsmethode nicht async ist) ---- ASP.NET MVC App-Code ----
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-Code ----
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;
}
In Ihrem Fall befreien Sie einige Ressourcen, wenn Sie sagen, warten Sie. Sie können jedoch verbessern, indem Sie tasks.whenall verwenden - bitte lesen Sie dies: http://msdn.microsoft.com/en-AU/library/hh556530.aspx – codebased