gpt4 book ai didi

c# - 在 .net 中的嵌套循环内执行异步方法时出现问题

转载 作者:行者123 更新时间:2023-11-30 13:38:53 24 4
gpt4 key购买 nike

我在嵌套循环中调用了一个异步函数,如下所示

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

打印出来的结果是

  • 第二个附件.txt
  • SecondAttachment.txt。

仅显示第二个附件(结果不正确)。

然后我尝试像下面这样同步执行相同的操作。

private static void AddAttachmentAsync(ExchangeEmailInformation information)
{
AddAttachment(information.UserAlias, information.EngagementName,
information.DocumentTransferId.ToString(), information.FileName,
information.FileSize.ToString(), information.ActivityName);


}

结果是

  • 第一个附件.txt

  • SecondAttachment.txt

如我所愿显示正确的结果

我该如何解决这些问题?

最佳答案

information 是在嵌套循环外声明的引用类型对象。您正在将此对象传递给您的 AddAttachmentAsync 方法,但在等待它完成(甚至开始处理 Task)之前,您已经在修改 信息在下一次迭代中。

在将信息发送到异步方法之前,您应该制作一份副本。

编辑 正如 Marc 指出的那样,这应该是一个具有复制值的新对象,而不仅仅是对同一对象的新引用。

关于c# - 在 .net 中的嵌套循环内执行异步方法时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14253889/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com