Thread.Sleep()或while()?

时间:2017-01-20 14:36:22

标签: c# multithreading winapi optimization

我有一个C#应用程序,我通过Windows API与另一个窗口进行交互:(例如,FindWindow()FindWindowEx())。

在我的应用程序的一个特定部分中,我必须等待其他应用程序的窗口加载,然后再单击出现的按钮(有时需要三秒钟才能显示)。

目前,我正在这样做:

IntPtr foohWnd = IntPtr.Zero;
while(foohWnd == IntPtr.Zero)
    foohWnd = FindWindow(null, "Foo");

正如您所看到的,这只是一遍又一遍地检查窗口而不关心资源或类似的东西。 (别担心,在我的实际代码中,为了防止无限循环,它会“超时”。)

但是,我发现这样做的另一种方法是使用Thread.Sleep()

Thread.Sleep(3000);
foohWnd = FindWindow(null, "Foo");

这两个中哪一个是更好的做法?有没有更好的方式我在这里无视?

2 个答案:

答案 0 :(得分:5)

尝试:

let number: number = 2;
let string = number as string;

console.log(typeof string); // "number"

这是异步方式,线程不会被阻止。

答案 1 :(得分:0)

你可以混合两个过程:

IntPtr foohWnd = IntPtr.Zero;
while(foohWnd == IntPtr.Zero)
{
    Thread.Sleep(1000);
    foohWnd = FindWindow(null, "Foo");
}

虽然会占用CPU,但是当窗口超过3秒后,睡眠不起作用。