简体   繁体   中英

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. Should i create a SQL-Database just for that single serial number or is there an easier way?

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.

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.

If memory serves, the FileStream class has constructors that can lock the file using FileShare options. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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