我在使用内存映射文件反序列化数据时有时会遇到异常,我不太清楚为什么。
以下是代码的重要部分:
//the class I am serializing
[ProtoContract]
public class Result
{
[ProtoMember(1)]
private Dictionary<string, string> _errorDict;
[ProtoMember(2)]
public Dictionary<string, string> ResultsDict { get; set; }
private readonly PipeStream _stream;
private readonly StreamWriter _writer;
private MemoryMappedFile _mmf;
public Result()
{
_errorDict = new Dictionary<string, string>();
}
public Result(string pipeHandle)
{
_errorDict = new Dictionary<string, string>();
ResultsDict = new Dictionary<string, string>();
if (pipeHandle != null)
{
_stream = new AnonymousPipeClientStream(PipeDirection.Out, pipeHandle);
_writer = new StreamWriter(_stream) { AutoFlush = true };
}
}
public void AddError(string file, string error)
{
_errorDict.Add(file, error);
}
public void Serialize()
{
_mmf = MemoryMappedFile.CreateOrOpen(FrConfig.CONFIG_FILE, FrConfig.CONFIG_FILE_SIZE);
using (MemoryMappedViewStream stream = _mmf.CreateViewStream())
{
Serializer.SerializeWithLengthPrefix(stream, this, PrefixStyle.Base128);
stream.Flush();
}
}
public static Result Deserialize()
{
using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting(FrConfig.CONFIG_FILE))
{
using (MemoryMappedViewStream stream = mmf.CreateViewStream())
{
return Serializer.DeserializeWithLengthPrefix<FrResult>(stream, PrefixStyle.Base128);
}
}
}
/// <summary>
/// Writes progress information to pipe.
/// </summary>
public void WriteToStream(object s)
{
if (_stream == null || _writer == null) return;
_writer.WriteLine(s);
_stream.WaitForPipeDrain();
}
}
//on the main thread:
private static void Main()
{
//spawn child process
//after returning from child process...
var r = FrResult.Deserialize();
}
//On child process
static void Main(string[] args)
{
var result = new FrResult(pipeHandle);
//perform processing
result.Serialize()
}
从子进程返回后调用Deserialize方法时,我会遇到以下异常:
发生FileNotFoundException抛出异常: &#39; System.IO.FileNotFoundException&#39;在System.Core.dll中 信息:无法找到指定的文件。
发生了System.IO.FileNotFoundException
HResult = -2147024894
消息=无法找到指定的文件。
来源= System.Core
StackTrace:
在System.IO .__ Error.WinIOError(Int32 errorCode,String maybeFullPath)
InnerException:
我不确定为什么有时会抛出此错误,也不知道解决此问题的最佳方法。