VSTO:在调用Excel的主线程 [英] VSTO: invoking on main Excel thread
问题描述
我有上启动一个新的线程做一些处理的Excel工作表的按钮。如果我想要到Excel的任何更改(例如,编写使用 Worksheet.Range(A1)的数据单元格值=信息;
),我想我必须使用主UI线程。
I have a button on an Excel sheet which starts a new thread to do some processing. If I want to make any changes to Excel (e.g. write data to a cell using Worksheet.Range("A1").Value = "info";
), I think I must use the main UI thread.
如何才能做到这一点?
通常,在的WinForms我称之为调用
在控制,但 Excel.Application
或工作表
或范围
对象不具有<code>调用方法。
Typically in Winforms I would call Invoke
on a control, but the Excel.Application
or Worksheet
or Range
objects don't have an Invoke
method.
推荐答案
这工作并不需要被在UI线程上完成的,.NET将元帅找你,但如果你从后台线程,你可能会碰到的一再呼吁。性能问题
That work doesn't 'need' to be done on the UI thread, .net will marshal the call for you, but if you make repeated calls from a background thread you may hit performance issues.
但具体回答你的问题,如果你有.NET 3.5,在外接负载事件补充一点:
But to answer your question specifically, if you have .net 3.5, in your add-in load event add this:
_dispatcher = Dispatcher.CurrentDispatcher;
然后添加:
And then add:
public Dispatcher Dispatcher { get {return _dispatcher;} }
然后你可以调度到UI线程转到
Then you can dispatch to the UI thread by going
Globals.ThisAdd.Dispatcher.Invoke(()=>{/*stuff*/});
如果您还没有.NET 3.5,然后有一些其他的线程同步技术,如使用SynchronizationContext.Current而不是调度。
If you don't have .net 3.5, then there are a few other thread synchronisation techniques, like using SynchronizationContext.Current instead of the Dispatcher.
这篇关于VSTO:在调用Excel的主线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!