Task.Factory.StartNew 和从外部组件打开表单的问题
我有一个主 Windows 应用程序项目和另一个类库应用程序。在类库应用程序中,我有一个表单(以编程方式创建),在长时间运行工作后显示在主 Windows 应用程序项目中。
我想异步显示该表单(在类库中)。
我为主应用程序项目编写了这段代码:
Task t = Task.Factory.StartNew(delegate
{
if (this.InvokeRequired)
{
this.Invoke((Action)(() => textBox1.Text += "Enter Task"));
this.Invoke((Action)(() =>
{
ExternalAssembly.OpenForm of = new ExternalAssembly.OpenForm();
of.ShowWindow();
}));
}
this.Invoke((Action)(() => textBox1.Text = textBox1.Text + Environment.NewLine + "Exit Task"));
}, CancellationToken.None, TaskCreationOptions.None);
并在类库中:
public class OpenForm
{
public void ShowWindow()
{
Thread.Sleep(10000);
Form1 frm = new Form1();
frm.ShowDialog();
}
}
但是当类库中的表单显示时,我的主表单冻结了。如何更改代码以便在另一个程序集中异步显示表单?
多谢。
I have a main Windows Application Project and another Class library application. In the class library app, I have a form (created programatically) that shows in main windows application project after long running work.
I want to show that form (in class library) asynchronously.
I wrote this code for Main Application Project:
Task t = Task.Factory.StartNew(delegate
{
if (this.InvokeRequired)
{
this.Invoke((Action)(() => textBox1.Text += "Enter Task"));
this.Invoke((Action)(() =>
{
ExternalAssembly.OpenForm of = new ExternalAssembly.OpenForm();
of.ShowWindow();
}));
}
this.Invoke((Action)(() => textBox1.Text = textBox1.Text + Environment.NewLine + "Exit Task"));
}, CancellationToken.None, TaskCreationOptions.None);
and in class library:
public class OpenForm
{
public void ShowWindow()
{
Thread.Sleep(10000);
Form1 frm = new Form1();
frm.ShowDialog();
}
}
But when the form in the class library shows, my main form freezes. How I can change the code so that showing a form in another assembly is asynchronous?
Thanks a lot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您已使用
Task.Factory.StartNew
启动了后台任务。然后,您在该后台任务中使用了Invoke
。这会在前台线程上运行该操作,并阻塞后台线程直到完成。由于您调用的代码 (
ShowWindow
) 需要很长时间,因此您已成功阻止前台和后台线程。You've started a background task by using
Task.Factory.StartNew
. You've then, in that background task, usedInvoke
. This runs the action on the foreground thread, blocking the background thread until it's completed.Since the code you're invoking (
ShowWindow
) takes a long time, you've successfully blocked both foreground and background threads.你可以尝试这样的事情
You could try something like this