From 99facf88ad11f3c0e9940ee610b4cb93484302e7 Mon Sep 17 00:00:00 2001 From: MLopez Date: Wed, 1 Feb 2023 19:41:29 -0700 Subject: [PATCH] ClsPaginas: Usar ThreadSafeRandom() en vez de Random() -RAZONAMIENTO: Random() no es thread safe, esto puede ocasionar problemas cuando dos hilos intenten acceder a la instancia de Random() y que termine generando puros ceros. En .NET Core 6.0 se introduce Random.Shared para compartir una instancia de Random() entre hilos distintos. https://learn.microsoft.com/en-us/dotnet/api/system.random.shared?view=net-7.0 Para .NET 4.8, se implementa la clase ThreadSafeRandom() que cumple la misma funcionalidad. Basado en https://stackoverflow.com/a/57962385/3529902 --- App_Code/ClsPaginas.vb | 4 +--- App_Code/ThreadSafeRandom.vb | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 3 deletions(-) create mode 100644 App_Code/ThreadSafeRandom.vb diff --git a/App_Code/ClsPaginas.vb b/App_Code/ClsPaginas.vb index 71f9a5e21..7aa2895e1 100644 --- a/App_Code/ClsPaginas.vb +++ b/App_Code/ClsPaginas.vb @@ -12,7 +12,6 @@ Imports Microsoft.Reporting.WebForms Imports Newtonsoft.Json Imports Newtonsoft.Json.Linq - 'NOTA AD TEAM 'COLOR PARA ROW TOTAL EN REPORT VIEWER: #67809F (AZULITO) @@ -46,8 +45,7 @@ Public Class ClsPaginas End Property #Region "Propiedades" - Private Shared ReadOnly Property Rand As New Random() - + Private Shared ReadOnly Property Rand As New ThreadSafeRandom() Private Property SubReportData As Modelos.MSubReportData Get Return If(IsNothing(ViewState("SubReportData")), Nothing, DirectCast(ViewState("SubReportData"), Modelos.MSubReportData)) diff --git a/App_Code/ThreadSafeRandom.vb b/App_Code/ThreadSafeRandom.vb new file mode 100644 index 000000000..825913ccb --- /dev/null +++ b/App_Code/ThreadSafeRandom.vb @@ -0,0 +1,15 @@ +Imports System.Threading + +NotInheritable Class ThreadSafeRandom + Private Shared ReadOnly GlobalRandom As New Random() + Private Shared ReadOnly LocalRandom As New ThreadLocal(Of Random)(Function() + + SyncLock GlobalRandom + Return New Random(GlobalRandom.Next()) + End SyncLock + End Function) + + Function [Next](Optional min As Integer = 0, Optional max As Integer = Integer.MaxValue) As Integer + Return LocalRandom.Value.Next(min, max) + End Function +End Class \ No newline at end of file