public void updateInTable(Entity Camel); //updates the table.
として私たちは、メソッドを持っている public Camel SendRequest(handler, uri, route, Camel); //basically takes all the parameters and provide you the Camel.
ような方法があります。独自のスレッドやタスクを作成する必要はありません。
すべての非同期メソッドは、Task
またはTask<T> value. You need to use the
を返します。keyword to await for the operation to complete asynchronously - that means the thread is released until the operation completes. When that happens, execution resumes after the
await`を返します。
PUTリクエストの書き込み方法は、hereです。例では、例えば、文字列にProduct
クラスをシリアル化し、正しいコンテンツタイプにStringContent
クラスを作成するために必要な定型コードを減らすためにPutAsJsonAsyncメソッドを使用しています。
var response = await client.PutAsJsonAsync($"api/products/{product.Id}", product);
response.EnsureSuccessStatusCode();
あなたは1000個の製品を入れたい場合は、すべてのあなた製品の配列やリストが必要です。あなたは、複数の呼び出しを行うためにLINQを使用して、彼らは最後に返す作業を待つことができます。
var callTasks = myProducts.Select(product=>client.PutAsJsonAsync($"api/products/{product.Id}", product);
var responses = await Task.WhenAll(callTasks);
これはあなたがいずれかが成功したかどうかをチェックすることができます前に終了するすべての要求を待つ必要があることを意味します。あなたは、応答自体を待つSelect
の体を変更することができます。
var callTasks = myProducts.Select(async product=>{
var response=await client.PutAsJsonAsync($"api/products/{product.Id}", product);
if (!response.IsSuccessStatusCode)
{
//Log the error
}
return response.StatusCode;
});
var responses=await Task.WhenAll(callTasks);
それは、しかし別の方法にラムダをCONVERするなどPutProductAsync良いでしょう:
async Task<HttpStatusCode> PutProduct(Product product,HttpClient client)
{
var response=await client.PutAsJsonAsync($"api/products/{product.Id}", product);
if (!response.IsSuccessStatusCode)
{
//Log the error
}
return response.StatusCode;
};
var callTasks = myProducts.Select(product=>PutProductAsync(product));
var responses=await Task.WhenAll(callTasks);
最初にサポートされている最も古いバージョンの.NETは4.5.2で、HTTPコールは 'HttpClient'で行われます。次に、HttpClientのメソッドはすべて*非同期です。たとえば、 'HttpClient.PutAsync()'がバックグラウンドで実行されます。スレッドをバックグラウンドで実行するためにスレッドを使用する必要はありません。あなたは 'myUrlObjectPairss.Select(data => client.PutAsync(data.url、data.Content))。ToArray()'と書いて、すべての呼び出しを並行して開始することもできます。 –
悪いです。私たちはC#6を使用しています。私は誤って他のC#4を追加しました。 – Vicky
@Vicky - あなたが追加した署名のタイプが一貫していません。これがあなたの本当のコードであるという方法はありません。助けが必要な場合は、可能な限り簡単に回答できるように努力してください。私たちには[mcve]が必要です。 – Enigmativity