用任务阻塞?

发布于 2024-12-20 12:17:51 字数 315 浏览 3 评论 0原文

我尝试在我的应用程序中使用这样的任务:

Task test;
test = Task.Factory.StartNew(() => general.Login(loginName, password));
MyTextBox.Text = "test text";

UI 线程将进行此调用,我需要将其阻塞,直到工作线程从服务返回,但我不希望 UI 冻结。

我可以使用ContinueWith,但这会分割我的登录方法,这使得它更难以遵循。我还需要主 UI 线程来运行此方法中的其余代码。

我该如何解决这个问题?

I try to use tasks in my application like this :

Task test;
test = Task.Factory.StartNew(() => general.Login(loginName, password));
MyTextBox.Text = "test text";

It will be the UI thread that makes this call and I need it to be blocked until the worker thread returns from the service but I do not want the UI to freeze.

I could use a ContinueWith but this will split my login method and this makes it harder to follow. I do also need the main UI thread to run the rest of the code in this method.

How do I solve this?

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

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

发布评论

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

评论(2

中性美 2024-12-27 12:17:51

这正是 C# 5 中的 async 解决的问题。目前,您基本上必须拆分代码。虽然很痛苦,但事情就是这样。 (顺便说一句,您的描述略有偏差 - 您不想想要阻止 UI 线程...您希望在工作线程返回之前“不执行逻辑的第二部分”。不完全相同的事情:)(您可能还想禁用 UI 的其他一些部分,但我们不能确定。)

值得在异步功能上先行一步 - 请参阅 Visual Studio 异步主页,提供大量资源。

This is precisely the problem that async in C# 5 solves. For the moment, you basically have to split your code. It's a pain, but that's the way it is. (Your description is slightly off, by the way - you don't want to block the UI thread... you want to "not perform the second part of your logic" until the worker thread returns. Not quite the same thing :) (You may also want to disable some other bits of the UI, but we can't tell for sure.)

It's worth getting a head start on the async feature - see the Visual Studio async home page for a lot of resources.

高速公鹿 2024-12-27 12:17:51

没有办法在不阻塞等待线程的情况下等待线程。你可以做的是这样的:

fire task
do some other task
wait for task  // hopefully the task finished by now

There is no way to wait for a thread without blocking the waiting thread. What you can do is something like:

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