防止过程变得无法响应

问题描述 投票:-3回答:1

我的程序必须做一些繁重的计算。由于计算原因,整个过程在几秒钟后没有响应,而CPU使用率保持在20%左右,内存使用率约为100 MB。

有没有一种通用的方法来保持Windows窗体应用程序在进行大量计算时的响应?

c# winforms
1个回答
0
投票

您所要做的就是将繁重的计算移动到不同的线程。 以下是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.");

    }
}

还有一些文档,以防您需要: https://docs.microsoft.com/en-us/dotnet/standard/threading/using-threads-and-threading https://www.tutorialspoint.com/csharp/csharp_multithreading.htm

还有一个在线程中启动函数的简短方法: C# Call a method in a new thread

© www.soinside.com 2019 - 2024. All rights reserved.