1

此 C# 代码位于 .NET 4.5ComVisible程序集中:

C# 代码

[InterfaceType(ComInterfaceType.InterfaceIsDual)]
[Guid("22341223-9264-12AB-C1B4-B4F112014C31")]
public interface IComWithTask
{
    void LongExecutionMethod(double x);
    void LongExecutionMethodAsync(double x);
}

[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
[Guid("23844123-9274-12CB-C1F4-B4F1521E4F33")]
public interface IComWithTaskEvents
{
    void OnLongExecutionMethodComplete(double x);
}

[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(IComWithTaskEvents))]
[Guid("E4F27AA4-1932-2196-1234-121CF2722C42")]
[ProgId("ComWithTask")]
public class ComWithTask : IComWithTask
{
    [ComVisible(false)]
    public delegate void LongExecutionMethodComplete(double x);
    public event LongExecutionMethodComplete OnLongExecutionMethodComplete;

    public void LongExecutionMethod(double x)
    {
        if (OnLongExecutionMethodComplete != null)
        {
            OnLongExecutionMethodComplete(x * x);
        }
    }

    public void LongExecutionMethodAsync(double x)
    {
        Task.Factory.StartNew(state =>
        {
            var onLongExecutionMethodComplete = OnLongExecutionMethodComplete;
            if (onLongExecutionMethodComplete != null)
            {
                onLongExecutionMethodComplete(x * x);
            }
        }, null);
    }
}

从 Excel 2010 32bit VBA,我有以下行为:

VBA 代码

Private WithEvents oComWithTask As ComWithTask

Public Sub Class_Initialize()
    Set oComWithTask = New ComWithTask
End Sub

Public Sub LongExecutionMethod()
    ' Works as expected
    Call oComWithTask.LongExecutionMethod(2)
End Sub

Public Sub LongExecutionMethodAsync()
    ' Does NOT work!
    Call oComWithTask.LongExecutionMethodAsync(3)
End Sub

Private Sub oComWithTask_OnLongExecutionMethodComplete(ByVal x As Double)
    MsgBox x
End Sub

我知道我在调用 .NET 时正在旋转一个线程LongExecutionMethodAsync,并且我知道办公应用程序是单线程的。

我确实找到了关于以多线程方式从 .NET 调用 COM 组件的优秀文献,但找不到任何相反的资源,即 VBA 调用使用 COM 方法包装的多线程 .NET。

关于如何LongExecutionMethodAsync使用多线程工作的任何想法,你能指出我关于这个主题的任何相关资源吗?另外,您对在 VBA 中触发异步事件有其他建议吗?

4

1 回答 1

1

上面的代码按预期工作,问题是 VBA 中对象的生命周期,它在事件引发之前就死了。

于 2012-10-24T10:14:06.010 回答