UI 线程上的方法超时

发布于 2024-07-18 10:19:45 字数 238 浏览 4 评论 0原文

我遇到的问题是在 UI 线程 (WinForms) 上实例化一个对象。 这个对象创建可能需要很长时间,我希望该方法有某种“超时”(因为它阻止了我的应用程序)。

我遇到的问题是: 1.该对象必须在UI线程上创建 2.该对象是外部对象,我没有任何源访问权限,因此无法修改它。

所以我的问题是,如果有人有一个创造性的想法,是否可以创建一个逻辑,在达到超时时停止执行方法?

蒂亚 马丁

I have the problem that I'm instanciating an object on the UI-thread (WinForms).
This object creation probably takes very long, and I would like to have some sort of a "timeout" for that method (because it's blocking my app).

The problems I have are:
1. the object must be created on the UI thread
2. the object is a foreign object, and I don't have any source access, so I cannot modify it.

So me question would be, if somebody has a creative idea, if it is possible to create a logic which stops the method for been executed if a timeout is reached?

tia
Martin

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

抚笙 2024-07-25 10:19:46

并不真地; 尤其如果您无权访问源代码。

即使可以,在没有充分理由的情况下强行中断代码也不是一个好主意 - 它只会导致问题(泄漏、锁被锁定等)。

它必须是相同 UI 线程吗? 您可以生成第二个 UI 线程来拥有此代码吗? 它有点斗志旺盛,但可以工作。

Not really; especially if you don't have access to the source.

Even if you could, it isn't a good idea to forcibly interrupt code without good reason - it can only lead to problems (leaks, locks being left locked, etc).

Does it have to be the same UI thread? You could spawn a second UI thread to own this code? It gets a little scrappy, but can work.

耶耶耶 2024-07-25 10:19:46

如果您使用 BeginInvoke,则 IAsyncResult 需要等待您可以从非 UI 线程等待 WaitOne(timeout) 的句柄。

不幸的是,在超时时,没有干净的方法来取消 BeginInvoke - 因此您可以尝试 1800 INFORMATION 的解决方案。

if you're using BeginInvoke, the IAsyncResult has a wait handle on which you can WaitOne(timeout) - from the non-UI thread.

Unfortunately, on timeout, there is no clean way to cancel that BeginInvoke - so you may try 1800 INFORMATION's solution.

小姐丶请自重 2024-07-25 10:19:45

这是一个糟糕的解决方案。 使用计时器上的工作线程来监视 UI 线程。 如果在创建对象之前计时器已过,请让工作线程在 UI 线程上调用 Abort。 这将在 UI 线程中引发 ThreadAbortException,您必须捕获该异常。 这样做不好的原因是,根据引发异常的微妙时间和竞争条件,您可能会导致程序挂起或崩溃。

一个“更安全”的方法是让工作线程调用 Interrupt - 这会在 UI 线程中引发 ThreadInterruptedException,但仅当它处于 WaitSleepJoin 时才有效。 code> state - 如果线程从不休眠,它不会中断,但至少它不会挂起或损坏内存。

Here is a bad solution. Use a worker thread on a timer to monitor the UI thread. If the timer elapses before the object is created, have the worker thread call Abort on the UI thread. This will raise a ThreadAbortException in the UI thread which you must catch. The reasons why this is bad is because you can cause your program to hang or crash depending on subtle timing and race conditions for when the exception is raised.

A "safer" method is to have the worker call Interrupt - this will raise a ThreadInterruptedException in the UI thread, but only when it is in the WaitSleepJoin state - if the thread never sleeps it will not interrupt, but at least it won't hang or corrupt memory either.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文