Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 794473
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T22:19:08+00:00 2026-05-14T22:19:08+00:00

What is the correct way of generating random numbers in an ASP.NET MVC application

  • 0

What is the correct way of generating random numbers in an ASP.NET MVC application if I need exactly one number per request? According to MSDN, in order to get randomness of sufficient quality, it is necessary to generate multiple numbers using a single System.Random object, created once. Since a new instance of a controller class is created for each request in MVC, I cannot use a private field initialized in the controller’s constructor for the Random object. So in what part of the MVC app should I create and store the Random object? Currently I store it in a static field of the controller class and lazily initialize it in the action method that uses it:

public class HomeController : Controller
{
    ...

    private static Random random;

    ...

    public ActionResult Download()
    {
        ...

        if (random == null)
            random = new Random();

        ...

    }
}

Since the “random” field can be accessed by multiple instances of the controller class, is it possible for its value to become corrupted if two instances attempt to initialize it simultaneously? And one more question: I know that the lifetime of statics is the lifetime of the application, but in case of an MVC app what is it? Is it from IIS startup till IIS shutdown?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T22:19:08+00:00Added an answer on May 14, 2026 at 10:19 pm

    Ideally you want to maintain an instance of the Random class for longer than the lifetime of a single page. Do not do this by putting it in a static variable; the Random class is not thread-safe and this will result in problems. From the docs:

    Any instance members are not guaranteed to be thread safe.

    My favourite approach is the RandomGen2 wrapper class from the Microsoft ParallelFX team (who really know what they’re doing with threading) which uses an instance per thread for (mostly) lock-free and thread-safe random numbers.

    public static class RandomGen2 
    { 
        private static Random _global = new Random(); 
        [ThreadStatic] 
        private static Random _local;
    
        public static int Next() 
        { 
            Random inst = _local; 
            if (inst == null) 
            { 
                int seed; 
                lock (_global) seed = _global.Next(); 
                _local = inst = new Random(seed); 
            } 
            return inst.Next(); 
        } 
    }
    

    Which you can then just call as follows:

    var rand = RandomGen2.Next();
    

    You may need to add extra methods to wrap the other Random methods you want to access, and I’d suggest a better name such as ThreadSafeRandom, but it demonstrates the principle.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm generating HTML dynamically using Delphi strings (Delphi XE). What is the correct way
I am generating a random number admission no and this is my DAL public
I am generating a random number and checking if the character contained is a
I'm dynamically generating a textbox and a dropdownlist in my ASP.NET web app table
How would you correct way to handle an exception in this situation? Initially I
What is the correct way to add a product variant? I create the product
What's the correct way to set a flash message for the current view but
Which is correct way to extend/subclass components? Ext.define('Holidays.Components.UserInfo', { extend: 'Ext.panel.Panel', alias: 'widget.UserInfo', region:
What is the correct way to use pygame.Color names when using unicode_literals ? Python
What is the correct way to draw isometric tiles in a 2D game? I've

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.