C# 创建增加 1 的全局数 [英] C# Creating global number which increase by 1
问题描述
我正在编写简单的银行账户教程程序.对于每个注册的新客户,帐号将增加 1,以获取新 ID.我在C# Mueller"一书中看到了例子.我只是好奇这是否是进行此操作的正确方法,它将如何处理并发注册?有没有更好的方法来处理这个问题,也许使用单例或全局变量,内存缓存?在实际应用中如何处理这样的项目?
I am writing simple bank account tutorial program. For each new customer which enrolls, the account number will be incremented by 1, for a new id. I saw example in "C# Mueller" book. I am just curious if this is proper way to conduct this, how will it handle concurrency enrollments? Is there a better to handle this, maybe with Singletons or global variables, memory cache? How would item like this be handled in real world application?
public class BankAccount
{
private static int _nextAccountNumber = 1000;
private int _accountNumber;
private double _balance;
public void InitBankAccount()
{
_accountNumber = ++_nextAccountNumber;
_balance = 0.0;
}
public void Deposit(decimal amount)
{
_balance += amount;
}
etc...
这个网站也很有用:https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/lock-statement
推荐答案
你所做的没问题,但不是线程安全的.thepirat000 在评论中提到您可以使用 lock 语句.
What you are doing is ok, but not thread safe. thepirat000 mentioned in a comment that you could use a lock statement.
private static object acctNumLock = new object();
…
lock(acctnumLock) {
_accountNumber = ++_nextAccountNumber;
}
您还应该考虑使用 Interlock.Increment 方法效率更高.lock 语句允许您锁定"(一次只允许一个线程访问)一个语句块.Interlock.Increment 是一个原子操作,它只做一件事(即增加一个值),但这样做的方式是确保在线程切换之前完成操作.两者都提供线程安全.
You should also consider using the Interlock.Increment method which is more efficient. The lock statement allows you to 'lock' (allow only one thread access at a time) to a block of statements. The Interlock.Increment is an atomic operation, that only does one thing (namely increment a value), but does so in a way that ensures the operation is completed before the thread switches. Both provide thread safety.
有没有更好的办法?这是一个很难回答的问题,因为这取决于您要尝试做什么.我怀疑实际的银行应用程序会取消数据库锁并使用特定算法来生成帐号(即一个更复杂的过程).如果您只是想为简单的应用程序生成唯一值,那么您所拥有的应该可以正常工作.
Is there a better way? That's a very difficult question to answer because it depends on what you are trying to do. I suspect that actual banking applications take out DB locks and use specific algorithms to generate account numbers (i.e. a much more complicated process). If you are just trying to generate unique values for simple applications what you have should work fine.
这篇关于C# 创建增加 1 的全局数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!