C# StreamWriter跳过要在foreach循环中序列化的项

C# StreamWriter跳过要在foreach循环中序列化的项,c#,streamwriter,C#,Streamwriter,在foreach循环中序列化大量对象时,我遇到了StreamWriter方面的问题。这是我的密码: public bool Export(ItemToSerialize it){ try{ using(StreamWriter sw = new StreamWriter(Path.Combine(MySettings.ExportPath, randomFileName + ".xml"))){ XmlSerializer ser = new XmlSeriali

在foreach循环中序列化大量对象时,我遇到了StreamWriter方面的问题。这是我的密码:

 public bool Export(ItemToSerialize it){
   try{
     using(StreamWriter sw = new StreamWriter(Path.Combine(MySettings.ExportPath, randomFileName + ".xml"))){
       XmlSerializer ser = new XmlSerializer(typeof(ItemToSerialize));    
       ser.Serialize(sw,it);
      }
      return true;
    } 
    catch{throw;}
 } 

public bool ExportAll(){
  List<ItemToSerialize> lst = RetrieveListToSerialize();
  foreach(ItemToSerialize it in lst){
    Export(it);
  }
}
public bool导出(ItemToSerialize){
试一试{
使用(StreamWriter sw=new StreamWriter(Path.Combine(MySettings.ExportPath,randomFileName+“.xml”)){
XmlSerializer ser=新的XmlSerializer(typeof(ItemToSerialize));
序列化(软件,it);
}
返回true;
} 
接住{throw;}
} 
公共bool ExportAll(){
List lst=RetrieveListToSerialize();
foreach(项目在lst中序列化){
出口(it);
}
}
当我有很多数据要导出时,它会跳过大部分数据。起初,我认为我必须刷新写入程序,但导出完成后刷新/关闭不会改变任何东西

令人惊讶的是,当我添加一个sleep(
System.Threading.Thread.sleep(1000)
)时,它就工作了。最令人惊讶的是,当我以500毫秒的速度停止睡眠时,它总是跳过其中一些

我怀疑它的书写速度超过了作者打开/关闭或简单书写的速度。但是,我希望导出函数在文件完全写入之前不会返回。使用StreamWriter写作时是否有类似于“背景”任务的任务

因为使用提供的代码,我真的不理解这种行为


谢谢

你确定,
randomFileName
确实是随机的吗?
randomFileName
是如何创建的?它是基于
DateTime.Now
?没错,随机文件名是这样写的:
string.Format(“[前缀]{0}{1}”),DateTime.Now.ToString(“yyyymmddhhmms”),userID)
。但由于它在一秒钟内处理多个文件,我猜该文件已经存在。然而,它为什么不引发异常,比如文件已经存在?谢谢你们两个!编辑:使用
DateTime.Now.ToString(“yyyymmddhhmmssfffff”)
进入毫秒级