【问题标题】:Prevent process from turning unresponsive防止进程变得无响应
【发布时间】:2019-02-08 13:13:13
【问题描述】:

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

在进行大量计算时,是否有一种通用方法可以让 Windows 窗体应用程序保持响应?

【问题讨论】:

  • 您正在创建531 billion 字符数组???我很惊讶它并没有完全崩溃。
  • 定义“非活动”真的很有帮助。你的意思是反应迟钝?或者它只是从字面上停止做任何事情并且CPU使用率下降到0%......我猜你可能需要阅读一些关于如何在长时间运行工作时保持Windows窗体应用程序响应(使用异步和工作线程) ) 但请用更具体的细节更新问题。
  • @JustShadow 不是反对票,但像这样的典型问题没有代码会吸引反对票和关闭票。您的答案也可能会吸引反对票,因为它只有答案链接。小心行事。

标签: c# winforms


【解决方案1】:

您所要做的就是将繁重的计算转移到不同的线程。
这是来自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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-20
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多