C# 运行此函数以在后台工作
这些函数工作得很好,但我不能强迫它在后台工作而不中断UI的使用C# 运行此函数以在后台工作,c#,asynchronous,background,task,.net-4.5,C#,Asynchronous,Background,Task,.net 4.5,这些函数工作得很好,但我不能强迫它在后台工作而不中断UI的使用 这不是游戏核心源代码的一个片段,它完全是外部程序读取进程内存,所以我在.NET 4.5中没有任何超能力,你可以使用任务。运行来完成。我还将更改方法以返回结果任务。通过这种方式,代码的客户端可以选择是等待结果,还是忽略结果(如果用户希望点火并忘记) private void CommandtWatcher() { // Both PR and D2H are classes from external
这不是游戏核心源代码的一个片段,它完全是外部程序读取进程内存,所以我在.NET 4.5中没有任何超能力,你可以使用
任务。运行来完成。我还将更改方法以返回结果任务
。通过这种方式,代码的客户端可以选择是等待结果,还是忽略结果(如果用户希望点火并忘记)
private void CommandtWatcher()
{
// Both PR and D2H are classes from external dll files
// PR is ProcessMemoryReader class, it reads a message from X window
if(PR[0].getLastChatMsg().Equals("#eg")) // If I typed "#eg" then
{
D2HList[0].QuitGame("WindowToBeClosed"); // Close game window
}
}
在.NET 4.5中,可以使用Task.Run
来执行此操作。我还将更改方法以返回结果任务
。通过这种方式,代码的客户端可以选择是等待结果,还是忽略结果(如果用户希望点火并忘记)
private void CommandtWatcher()
{
// Both PR and D2H are classes from external dll files
// PR is ProcessMemoryReader class, it reads a message from X window
if(PR[0].getLastChatMsg().Equals("#eg")) // If I typed "#eg" then
{
D2HList[0].QuitGame("WindowToBeClosed"); // Close game window
}
}
这个怎么样:
private Task CommandtWatcher()
{
return Task.Run(() =>
{
// Both PR and D2H are classes from external dll files
// PR is ProcessMemoryReader class, it reads a message from X window
if(PR[0].getLastChatMsg().Equals("#eg")) // If I typed "#eg" then
{
D2HList[0].QuitGame("WindowToBeClosed"); // Close game window
}
}
}
要在后台运行,请执行以下操作:
private void CommandtWatcher()
{
while (true)
{
// Both PR and D2H are classes from external dll files
// PR is ProcessMemoryReader class, it reads a message from X window
if(PR[0].getLastChatMsg().Equals("#eg")) // If I typed "#eg" then
{
D2HList[0].QuitGame("WindowToBeClosed"); // Close game window
return;
}
Thread.Sleep(100); // Prevent hogging cpu
}
}
这将在一个新线程中运行该方法,与UI分开,等待LastChatMsg
成为#eg
,然后执行逻辑并停止。这样如何:
private Task CommandtWatcher()
{
return Task.Run(() =>
{
// Both PR and D2H are classes from external dll files
// PR is ProcessMemoryReader class, it reads a message from X window
if(PR[0].getLastChatMsg().Equals("#eg")) // If I typed "#eg" then
{
D2HList[0].QuitGame("WindowToBeClosed"); // Close game window
}
}
}
要在后台运行,请执行以下操作:
private void CommandtWatcher()
{
while (true)
{
// Both PR and D2H are classes from external dll files
// PR is ProcessMemoryReader class, it reads a message from X window
if(PR[0].getLastChatMsg().Equals("#eg")) // If I typed "#eg" then
{
D2HList[0].QuitGame("WindowToBeClosed"); // Close game window
return;
}
Thread.Sleep(100); // Prevent hogging cpu
}
}
这将在新线程中运行该方法,与UI分开,等待LastChatMsg
被#eg
,然后执行逻辑并停止。您使用的是哪个版本的.NET?这会影响后台任务启动的难易程度。我有一个.NET 4.5版本用于此项目:)在这种情况下,我建议@NedStoyanov回答您使用的是.NET的哪个版本?这会影响后台任务启动的难易程度。我有一个用于此项目的.NET 4.5版本:)在这种情况下,我建议@NedStoyanov的答案我会使用wait task。延迟这种方式你在睡觉时不会用完线程。我会使用wait task。延迟这种方式你在睡觉时不会用完线程。