我想在每个页面请求中创建一个整数序列
这是我的代码:
Public Class Test
Inherits System.Web.UI.Page
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'integer sequence is created here
Static Sequence As Int32 = 0
Sequence = Sequence + 1
End Sub
End Class
我的要求是使用VB.NET代码创建序列,没有数据库帮助。序列必须从1开始并递增1.我尝试解决此问题的方法是在Page_Load中使用STATIC变量,该变量可以保留序列值。但有人告诉我,我的方法存在风险,因为它不是线程安全的。真的吗?或者我如何为每个请求创建一个序列,这个序列没有线程安全或其他问题?
我试图以另一种方式解决问题。但我不确定我的新解决方案的线程安全性。这是我的代码,对Singleton.Instance.Sequence
函数的调用将生成一个新的序列值:
Public NotInheritable Class Singleton
Private Sub New()
End Sub
Public Shared ReadOnly Property Instance() As Singleton
Get
Return Nested.instance
End Get
End Property
Private Class Nested
Shared Sub New()
End Sub
Friend Shared ReadOnly instance As New Singleton
End Class
Private count As Int32
Public Function Sequence() As Int32
count = count + 1
Return count
End Function
End Class
我的新解决方案线程是否安全?欢迎任何替代解决方案!
答案 0 :(得分:1)
您可以通过微小的修改使您的第一个解决方案成为线程安全的:
Public Class Test
Inherits System.Web.UI.Page
Static Sequence As Int32 = 0
Private Shared lockObject As New Object
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SyncLock lockObject
Sequence += 1
End SyncLock
End Sub
End Class
答案 1 :(得分:1)