我的程序必须做一些繁重的计算。几秒钟的计算导致整个过程变得无响应,而CPU使用率保持在20%左右,内存使用率保持在100 MB左右。
是否有一种通用方法可以使Windows窗体应用程序在进行大量计算时保持响应速度?
答案 0 :(得分: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