用任务阻塞?
我尝试在我的应用程序中使用这样的任务:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这正是 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.
没有办法在不阻塞等待线程的情况下等待线程。你可以做的是这样的:
There is no way to wait for a thread without blocking the waiting thread. What you can do is something like: