C#创建增加1的全局数字 [英] C# Creating global number which increase by 1
问题描述
我正在编写简单的银行帐户教程程序。对于每个注册的新客户,对于新的ID,帐号将增加1。
我在 C#Mueller书中看到了示例。我很好奇,如果这是执行此操作的正确方法,它将如何处理并发注册?是否有更好的方法来处理此问题,例如使用Singletons或全局变量,内存缓存?
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/zh- us / dotnet / csharp / language-reference / keywords / lock-statement
推荐答案
您在做什么就可以了,但不是线程安全的。
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屋!