带有 VSTO 插件的 c# Winform 控件保持 Excel 响应
c# Winform Controls with VSTO addin keep Excel responsive
我是 VSTO Excel 插件和 Winforms 的新手。我创建了一个插件,它启动了一个带有几个复选框、一个按钮和一个标签的 winform 页面来跟踪状态。
winform 一启动,我的 excel 就没有响应。我想让 excel 即使在 winform 打开时也能响应(并单击 "Done" 按钮)。按钮将 运行 一个漫长的 运行ning 过程。我怎样才能做到这一点?任何指针?
这就是我的
色带 Class:
public partial class Ribbon1
{
private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
{
}
private void button1_Click(object sender, RibbonControlEventArgs e)
{
Form1 fs = new Form1();
fs.ShowDialog();
}
}
表格Class:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private async void button1_Click(object sender, EventArgs e)
{
label1.Text = "Processing please wait";
await Task.Run(() => { longRunningProcess(); });
label1.Text = "File 1 Processed";
}
public void longRunningProcess()
{
Thread.Sleep(5000);
}
}
更新:
使用 .show 有效,但我无法访问 label1.Text 并收到错误消息:
System.InvalidOperationException: 'Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on.'
使用 Show
打开表单并使用 Invoke
编组回 UI 线程。
@Sievajet 帮助解决了这个问题。发布代码,以防有人需要它。
private async void button1_Click(object sender, EventArgs e)
{
label1.Text = "Processing please wait";
await Task.Run(() => { longRunningProcess(); });
label1.Invoke((MethodInvoker)delegate {
label1.Text = "File 1 Processed";
});
}
我是 VSTO Excel 插件和 Winforms 的新手。我创建了一个插件,它启动了一个带有几个复选框、一个按钮和一个标签的 winform 页面来跟踪状态。
winform 一启动,我的 excel 就没有响应。我想让 excel 即使在 winform 打开时也能响应(并单击 "Done" 按钮)。按钮将 运行 一个漫长的 运行ning 过程。我怎样才能做到这一点?任何指针?
这就是我的 色带 Class:
public partial class Ribbon1
{
private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
{
}
private void button1_Click(object sender, RibbonControlEventArgs e)
{
Form1 fs = new Form1();
fs.ShowDialog();
}
}
表格Class:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private async void button1_Click(object sender, EventArgs e)
{
label1.Text = "Processing please wait";
await Task.Run(() => { longRunningProcess(); });
label1.Text = "File 1 Processed";
}
public void longRunningProcess()
{
Thread.Sleep(5000);
}
}
更新: 使用 .show 有效,但我无法访问 label1.Text 并收到错误消息:
System.InvalidOperationException: 'Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on.'
使用 Show
打开表单并使用 Invoke
编组回 UI 线程。
@Sievajet 帮助解决了这个问题。发布代码,以防有人需要它。
private async void button1_Click(object sender, EventArgs e)
{
label1.Text = "Processing please wait";
await Task.Run(() => { longRunningProcess(); });
label1.Invoke((MethodInvoker)delegate {
label1.Text = "File 1 Processed";
});
}