C# で Excel 用の UDF ライブラリを作成中です。UDF を長時間実行するので、UDF を非同期にして、UDF の呼び出し中に Excel UI を引き続き使用できるようにします。以下は私のコードです。しかし、生成されたスレッドからExcelを呼び出すときに失敗します...
[ClassInterface(ClassInterfaceType.AutoDual)]
[ComVisible(true)]
[ComDefaultInterface(typeof(IRAPDataAddIn))]
public class RAPDataAddIn : IRAPDataAddIn
{
public string GetPositionData(Excel.Range Portfolios, Excel.Range Security)
{
Excel.Application excelApp = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
Excel.Range target = (Excel.Range)excelApp.get_Caller(System.Type.Missing);
Thread _workerThread = new Thread(new ParameterizedThreadStart(this.GetData));
_workerThread.CurrentCulture = System.Globalization.CultureInfo.CurrentCulture;
_workerThread.CurrentUICulture = System.Globalization.CultureInfo.CurrentUICulture;
_workerThread.Start(target);
return "Getting Data";
}
public void GetData(object Range)
{
Excel.Range target = Range as Excel.Range;
Thread.Sleep(1000);
object[,] returnData = new object[2,2];
returnData[0, 0] = " FirstThread";
returnData[0, 1] = " SecondThread";
returnData[1, 0] = " ThirdThread";
returnData[1, 1] = " FourthThread";
var Start = (Excel.Range)target.Worksheet.Cells[1,1];
var End = (Excel.Range)target.Worksheet.Cells[2,2];
Excel.Range r = (Excel.Range)target.Worksheet.Range[Start, End];
try
{
r.Value2 = returnData; ***//It fails here***
}
catch (Exception ex)
{
}
}