mercredi 11 septembre 2019

method completing faster than Convert.ToChar while generating random serial key, how to avoid this?

I am trying to generate random serial key strings with "####-####-####" format. When i run my codes (with a button click event), methods completing faster than parsing integer to char and that returns me a serial key string with all same chars (as like AAAA-AAAA-AAAA). But when i put there Thread.Sleep(50) then code works correctly.I am checking the converting time is less than a ms.I want to learn why this is happening and how to avoid them without Thread.Sleep . Thanks...

internal class GenerateNewLicence
{
    internal GenerateNewLicence()
    {
        FormReferrer.mainForm.text_licanceKey.Text = finalSegment();
    }
    private int generateASCII()
    {
        Random random = new Random();
        int generated = random.Next(65, 90);
        return generated;
    }
    private string fourthSegment()
    {            
        StringBuilder sBuild = new StringBuilder();
        for (int i = 0; i < 4; i++)
        {
            sBuild.Append(Convert.ToChar(generateASCII()));
            //Thread.Sleep(50);
        }
        return sBuild.ToString();
    }
    private string finalSegment()
    {
        StringBuilder builder = new StringBuilder();
        IEnumerable<int> _range = Enumerable.Range(0, 3);
        foreach (int i in _range)
        {
            if (i != 2)
            {
                builder.Append(fourthSegment() + "-");
            }
            else
            {
                builder.Append(fourthSegment());
            }
        }
        return builder.ToString();
    }
}




Aucun commentaire:

Enregistrer un commentaire