c# - 使集合可用于两个流程

标签 c# multithreading serialization dictionary io

大家好,我有一个必须在两个不同的exe文件之间共享的字典。第一个应用程序创建一个 key ,然后将其存储在字典中,然后另一个应用程序创建一个 key 并将其存储在字典中。

目前,我这样做:

private static void WriteToFile(Dictionary<string, byte[]> dictionary, string path)
    {
        Contract.Requires(dictionary != null);
        Contract.Requires(!string.IsNullOrEmpty(path));

        if (!(timestamp == File.GetLastWriteTime(DatabasePath)))
        {
            using (FileStream fs = File.OpenWrite(path))
            using (var writer = new BinaryWriter(fs))
            {
                // Put count.
                writer.Write(dictionary.Count);

                // Write pairs.
                foreach (var pair in dictionary)
                {
                    writer.Write(pair.Key);
                    writer.Write(pair.Value);
                }
                timestamp = DateTime.Now;
                File.SetLastWriteTime(DatabasePath, timestamp);

            }
        }
    }

    /// <summary>
    /// This is used to read a dictionary from a file
    /// http://www.dotnetperls.com/dictionary-binary
    /// </summary>
    /// <param name="path">The path to the file</param>
    /// <returns>The dictionary read from the file</returns>
    private static Dictionary<string, byte[]> ReadFromFile(string path)
    {
        Contract.Requires(!string.IsNullOrEmpty(path));
        var result = new Dictionary<string, byte[]>();
        using (FileStream fs = File.OpenRead(path))
        using (var reader = new BinaryReader(fs))
        {
            // Determine the amount of key value pairs to read.
            int count = reader.ReadInt32();

            // Read in all the pairs.
            for (int i = 0; i < count; i++)
            {
                string key = reader.ReadString();
                //// The byte value is hardcoded as the keysize is consistent
                byte[] value = reader.ReadBytes(513);
                result[key] = value;
            }
        }
        return result;
    }

然后,当我要存储 key 时,请调用此方法:
public static bool StoreKey(byte[] publicKey, string uniqueIdentifier)
    {
        Contract.Requires(ValidPublicKeyBlob(publicKey));
        Contract.Requires(publicKey != null);
        Contract.Requires(uniqueIdentifier != null);
        Contract.Requires(uniqueIdentifier != string.Empty);
        bool success = false;

        if (File.Exists(DatabasePath))
        {
            keyCollection = ReadFromFile(DatabasePath);
        }

        if (!keyCollection.ContainsKey(uniqueIdentifier))
        {
            if (!keyCollection.ContainsValue(publicKey))
            {
                keyCollection.Add(uniqueIdentifier, publicKey);
                success = true;

                WriteToFile(keyCollection, DatabasePath);
            }
        }
        return success;
    }

当程序生成 key 时,当我们尝试访问它们时,它只有1个 key ,我在做什么错?键和字符串存储得很好,但是我只是担心它们会覆盖文件或其他内容。

提前非常感谢您,任何帮助将不胜感激

PS:databasePath是我要保存的文件的路径,创建为字段。

最佳答案

很难说到底发生了什么,因为您没有提供有关字典中有多少项的信息,等等,但是当您从多个进程访问同一文件时,似乎遇到了某种文件访问问题。

您可以使用名为Mutex的跨进程同步对象,因此在访问文件之前,必须确保释放Mutex句柄,以便您可以获取所有权,其他进程可以在访问文件之前等待。

// Create a mutex
Mutex mutex = new Mutex(false, "DictionaryAccessMutex");

// Acquire an ownership
mutex.WaitOne();

// Release
mutex.ReleaseMutex();

编辑:新发现

另外,您尝试在读取后立即写,所以也许FileSystem操作尚未完成,所以写失败,我不确定在这种可能由.NET管理的类(如File/StreamReader/etc)中的100%已经处理了这种情况,但我相信值得仔细检查您的情况,因为还不能100%清楚地了解发生了什么。因此,只需尝试在读写操作之间添加一些超时,例如Thread.Sleep(500)

编辑:您可以做的另一件事是下载Process Monitor SysInternals utility,查看在访问给定文件时哪些操作失败。因此,只需添加一个新的过滤器Path=file name,您就可以看到底层的情况。

关于c# - 使集合可用于两个流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8489448/

相关文章:

c# - 为什么我不能通过字符串调用这个方法?

c# - asp.net mvc 可以自动生成时间戳到 js 代码吗?

python 子进程意外退出,退出代码为-9

c++ - 具有双端队列的c++任务线程中的竞争条件

java - Fork Join 优化

java - Java 中如何序列化属性?

java - 如何使用 Jackson 序列化基于 java.util.Map 的类

c# - 使用 VS 2013 Express for Desktop 获取本地 .mdf 数据库以与 WPF C# 应用程序一起使用

c# - 在 IValidatableObject 上设置 ValidationContext 的 Items 集合?

c# - 从基类派生的类的 XmlSerializer 构造函数错误