以下のようにネストされたループ内で非同期関数を呼び出しました
var queue = new Queue<ExchangeEmailInformation>(mailInformation);
var currentQueue = queue.ToList();
foreach (var exchangeEmailInformation in currentQueue)
{
ExchangeEmailInformation information = exchangeEmailInformation;
foreach (var queueList in exchangeEmailInformation.Attachment)
{
Attachment attachment = queueList;
information.FileName = attachment.Name;
var emailId = information.Sender.Split('@');
information.UserAlias = emailId[0];
information.FileSize = attachment.Size;
AddAttachmentAsync(information);
}
}
private static void AddAttachmentAsync(ExchangeEmailInformation information)
{
System.Threading.Tasks.Task.Factory.StartNew(
() =>
AddAttachment(information.UserAlias, information.EngagementName,
information.DocumentTransferId.ToString(), information.FileName,
information.FileSize.ToString(), information.ActivityName)).ContinueWith(
task => OnComplete(task, information), TaskContinuationOptions.None);
}
static void AddAttachment(string userAlias, string engagementName, string documentTranferId, string fileName, string fileSize,string activityName)
{
Console.Writeline(fileName);
}
In the exchange information collection has one record. In these collection there is another property called Attachment which type is AttachmentCollection which contain two attachments. After calling the method AddAttachmentAsync like above asynchronously the
印刷された結果は
- SecondAttachment.txt
- SecondAttachment.txt。
2番目の添付ファイルのみを表示しています(誤った結果)。
次に、以下のように同期的に実行しようとします。
private static void AddAttachmentAsync(ExchangeEmailInformation information)
{
AddAttachment(information.UserAlias, information.EngagementName,
information.DocumentTransferId.ToString(), information.FileName,
information.FileSize.ToString(), information.ActivityName);
}
結果は
FirstAttachment.txt
SecondAttachment.txt
思い通りに正しい結果を表示
これらの問題を解決するにはどうすればよいですか?