[英]Prevent process from turning unresponsive
我的程序必须做一些繁重的计算。 由于计算的原因,整个过程在几秒钟后变得无响应,而 CPU 使用率保持在 20% 左右,内存使用率保持在 100 MB 左右。
在进行大量计算时,是否有一种通用的方法可以使 Windows 窗体应用程序保持响应?
您所要做的就是将繁重的计算移动到不同的线程。
这是文档中的修改示例:
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#在新线程中调用方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.