XML ファイルを処理するために、Web API コントローラーで次の非同期コードを使用しています。すべてが期待どおりに機能しますが、これは async/await アプローチの正しい使用法です。基本的に、XML ファイルからすべての画像を抽出し、ディスクに保存しています。ファイルioの影響を最小限に抑えたいと思いました。
public async Task<HttpResponseMessage> PostFile()
{
await Task.WhenAll(this.ProcessProofOfPressenceImages(address, images, surveyReference), this.ProcessSketchImages(propertyPlans, images, surveyReference), this.ProcessExteriorImages(exteriorSketch, images, surveyReference));
//db code
}
private async Task ProcessProofOfPressenceImages(Dictionary<object, object> container, List<Dictionary<string, string>> images, string surveyReference)
{
if(images != null)
{
await Task.WhenAll(this.ProcessImagesHelper(container, images, surveyReference, "propertyImage"));
}
}
private async Task ProcessSketchImages(Dictionary<object, object> container, List<Dictionary<string, string>> images, string surveyReference)
{
if(images != null)
{
await Task.WhenAll(this.ProcessImagesHelper(container, images, surveyReference, "sketchPlanImage"), this.ProcessImagesHelper(container, images, surveyReference, "sketchFrontImage"), this.ProcessImagesHelper(container, images, surveyReference, "sketchRearImage"), this.ProcessImagesHelper(container, images, surveyReference, "sketchLeftSideImage"), this.ProcessImagesHelper(container, images, surveyReference, "sketchRightSideImage"));
}
}
private async Task ProcessExteriorImages(Dictionary<object, object> container, List<Dictionary<string, string>> images, string surveyReference)
{
List<Task> tasks = new List<Task>();
if(images != null)
{
await Task.WhenAll(this.ProcessImagesHelper(container, images, surveyReference, "image1"), this.ProcessImagesHelper(container, images, surveyReference, "image2"), this.ProcessImagesHelper(container, images, surveyReference, "image3"), this.ProcessImagesHelper(container, images, surveyReference, "image4"), this.ProcessImagesHelper(container, images, surveyReference, "image5"), this.ProcessImagesHelper(container, images, surveyReference, "image6"));
}
}
private async Task ProcessImagesHelper(Dictionary<object, object> container, List<Dictionary<string, string>> images, string surveyReference, string image)
{
if(container.ContainsKey(image) && !String.IsNullOrEmpty(container[image].ToString()))
{
using(MemoryStream memoryStream = new MemoryStream((byte[])container[image]))
{
string url = String.Format(@"{0}{1}{2}_{3}.jpg", EcoConfiguration.Instance.RootUrl, EcoConfiguration.Instance.SurveyImageRootUrl, surveyReference, image.SplitOnCapital("_"));
using(FileStream fileStream = new FileStream(url, FileMode.Create, FileAccess.Write))
{
Dictionary<string, string> imageDetails = new Dictionary<string, string>();
imageDetails.Add("TypeId", ((int)SurveyImageType.Exterior).ToString());
imageDetails.Add("ImageUrl", url);
if(container.ContainsKey(image + "Description"))
{
imageDetails.Add("Description", container[image + "Description"].ToSafeString());
}
images.Add(imageDetails);
await memoryStream.CopyToAsync(fileStream);
}
}
}
}
コメント/提案は大歓迎です。