ExcelAsyncUtil.Observer() in Async UDFs with RTD

43 views
Skip to first unread message

Tom Baxter

unread,
May 22, 2023, 9:44:49 AM5/22/23
to Excel-DNA
Hello,

We are hoping for some clarification.

We have an async UDF (i.e., static async Task<Object[,],>). When we call ExcelAsyncUtil.Observer() we see the exception indicating Observe() cannot be called from a ThreadSafe function. 

It feels like we are in a Catch-22 -- on one hand, the UDF needs to be async (ThreadSafe) but then we cannot, it seems, use the Observe() method. It seems a UDF that's async cannot call ExcelAsyncUtil.Observer().

Thanks..

Govert van Drimmelen

unread,
May 22, 2023, 10:19:04 AM5/22/23
to Excel-DNA
Your implementation will run async on a different thread, but there will be a wrapper that (for now) must not be marked as IsThreadSafe, and this wrapper will run on the main thread.

So you might have:

```
static async Task<object[,]> MyFunctionImpl(string arg1, int arg2) { ... real implementation here which will run on threadpool thread ... }

[ExcelFunction("My async function", IsThreadSafe=false)]
public static object MyFunction(string arg1, int arg2)
{
    // Gather call information
    var functionName = nameof(MyFunction);
    var parameters = new object[] { arg1, arg2 };

    // Call magic wrapper that will internally call ExcelAsyncUtil.Observer etc. - everything here is still running on the main thread
    return AsyncTaskUtil.RunTask(functionName, parameters, () => MyFunctionImpl(arg1, arg2));
}
```

You can get the AsyncTaskUtil helper by installing the ExcelDna.Registration package, or by grabbing the little bit of code you need from  here: 
and you'll also need these helpers:

-Govert

Tom Baxter

unread,
May 22, 2023, 5:58:21 PM5/22/23
to Excel-DNA
Thank you, Govert. Your explanation led me in the right direction. It's working the way I expect now.
Reply all
Reply to author
Forward
0 new messages