bc-csharp icon indicating copy to clipboard operation
bc-csharp copied to clipboard

ThreadedSeedGenerator sometimes freezes (on new threads, with debugger attached)

Open jkirsteins opened this issue 7 years ago • 1 comments

I wrote an application, which couldn't be debugged - the debugger would always freeze when stepping over a certain line. The line in question was invoking a function from a different library (Nethereum.Signer), which depends on Portable.BouncyCastle 1.8.1.1.

Without the debugger attached, the application would execute just fine.

After investigating, I determined that it would always happen when SecureRandom was first accessed on a new thread (if it was first accessed on the main thread, then the problem would not manifest).

I reduced the problem to the following example code:

static void InvokeBouncy(object _)
{
    new ThreadedSeedGenerator().GenerateSeed(32, true);
}
static void Main(string[] args)
{
    ThreadPool.QueueUserWorkItem(new WaitCallback(InvokeBouncy));
    Thread.Sleep(1000);
    Console.WriteLine("Execution will never get to this line (if the debugger is attached)");
}

This always hangs before the last line if the debugger is attached. It works fine when the application is run via dotnet run.

This specific example used Portable.BouncyCastle 1.8.1.2 and .NET Core 2.0 preview 2 on macOS.

One change, which solves this, is to add Thread.Yield(); to the ThreadedSeedGenerator.SeedGenerator.Run method, so that it looks like this:

private void Run(object ignored)
{
    while (!this.stop)
    {
        this.counter++;
        Thread.Yield();
    }
}

jkirsteins avatar Aug 17 '17 13:08 jkirsteins

Thanks, I had the same issue with the "BouncyCastle.NetCore" package version 1.8.5 and 1.8.8. Changing to the "BouncyCastle" package version 1.8.9 solved the issue.

If the ThreadedSeedGenerator is planned to be used in the future, this issue should definitely be solved.

bpiepiora avatar Oct 21 '21 14:10 bpiepiora