-3

My program has to do some heavy calculation. The whole process turns unresponsive after a few seconds in cause of the calculation, while the CPU usage stays somewhere around 20% and the memory usage around 100 MB.

Is there a general way to keep a Windows forms app responsive while doing heavy calculations?

LarsTech
  • 80,625
  • 14
  • 153
  • 225
  • 1
    You are creating `531 billion` character arrays??? I'm surprised it doesn't just crash altogether. – Ryan Wilson Feb 08 '19 at 13:14
  • It would really help to define "inactive". Do you mean unresponsive? Or it just literally stops doing anything and CPU usage drops to 0%...I am guessing that you may need to read up a bit on how to keep a Windows forms app responsive when doing long-running work (using async and worker threads) but please update the question with more concrete detail. – Stephen Byrne Feb 08 '19 at 13:49
  • 2
    @JustShadow Not the downvoter, but a typical question like this without code will attract down and close votes. Your answer could attract downvotes, too, since it just has links for an answer. Tread carefully. – LarsTech Feb 08 '19 at 15:09

1 Answers1

0

All you have to do is to just move that heavy calculation to different thread.
Here is a modified example from documentation:

using System;
using System.Threading;

public class ServerClass
{
    // The method that will be called when the thread is started.
    public void HeavyCalculation()
    {
        Console.WriteLine(
            "Heavy Calculation is running on another thread.");

        // Pause for a moment to provide a delay to make
        // threads more apparent.
        Thread.Sleep(3000);
        Console.WriteLine(
            "Heavy Calculation has ended.");
    }
}

public class App
{
    public static void Main()
    {
        ServerClass serverObject = new ServerClass();

        // Create the thread object, passing in the
        // serverObject.InstanceMethod method using a
        // ThreadStart delegate.
        Thread InstanceCaller = new Thread(
            new ThreadStart(serverObject.HeavyCalculation));

        // Start the thread.
        InstanceCaller.Start();

        Console.WriteLine("The Main() thread calls this after "
            + "starting the new InstanceCaller thread.");

    }
}

And some more documentation just in case you need:
https://learn.microsoft.com/en-us/dotnet/standard/threading/using-threads-and-threading
https://www.tutorialspoint.com/csharp/csharp_multithreading.htm

And a short way of starting a function in thread:
C# Call a method in a new thread

Just Shadow
  • 10,860
  • 6
  • 57
  • 75