简体   繁体   中英

Prevent process from turning unresponsive

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?

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://docs.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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM