简体   繁体   English

如何在我的 C# 应用程序中保存单个 Int(序列号)

[英]How to save a single Int(serial number) within my C# app

I try to manage a Serial number within my App, every time a new Product is created the serial number is incremented and should be saved.我尝试在我的应用程序中管理序列号,每次创建新产品时,序列号都会增加并且应该保存。 In an Older version of the Software the serial number was saved as plain text in a.txt File but i find that a bit error prone.在旧版本的软件中,序列号以纯文本形式保存在 a.txt 文件中,但我发现这很容易出错。 Should i create a SQL-Database just for that single serial number or is there an easier way?我应该为那个单一的序列号创建一个 SQL 数据库还是有更简单的方法?

I would not worry to much about creating a DB for saving the data.我不会太担心创建用于保存数据的数据库。 But another solution could be to save it as XML/JSON.但另一种解决方案可能是将其保存为 XML/JSON。

I'm not sure that the format of the file whether it be plain text, Json or XML is relevant here, rather you need to ensure that you lock the file properly.我不确定文件的格式是纯文本,Json 还是 XML 与此处相关,而是需要确保正确锁定文件。

If memory serves, the FileStream class has constructors that can lock the file using FileShare options.如果 memory 服务,则 FileStream class 具有可以使用 FileShare 选项锁定文件的构造函数。 This should be either None or Read whilst you open the file to update the counter - doing so will guarantee that the counter will operate properly in a multi-process environment.当您打开文件以更新计数器时,这应该是 None 或 Read - 这样做将保证计数器将在多进程环境中正常运行。

It is also possible to update a file without a lock provided that you can guarantee that there will only be one process using it - ie only your process and only one of them.也可以在没有锁的情况下更新文件,前提是您可以保证只有一个进程在使用它——即只有您的进程和其中一个。

You are basically trying to ensure that only one caller can update the file by eradicating race conditions either by ensuring only one caller, or by causing multiple callers to wait whenever one is already using the counter.您基本上是在尝试确保只有一个调用者可以通过消除竞争条件来更新文件,方法是确保只有一个调用者,或者当一个调用者已经在使用计数器时让多个调用者等待。

An SQL database would be a great approach, you could use an SQL Sequence which does all the locking and incrementing for you in a neat atomic function call, but might be a bit much in an application that doesn't already use a database engine. SQL 数据库将是一个很好的方法,您可以使用 SQL 序列,它在一个整洁的原子 ZC1C425268E68385D1AB5074C17A94F14 调用中为您完成所有锁定和递增,但可能已经在应用程序中使用了一个位引擎。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM