Today, I want to dive into a topic that has been both challenging and rewarding for me—writing plugins for Revit using C#. While I develop plugins for various platforms, Revit has truly captivated me with its versatility, thanks in large part to the powerful API developed by Autodesk
If you're just starting out with Revit plugin development, you're likely to encounter some roadblocks that aren't easily solved with a quick online search.
One common hurdle you might face is performing asynchronous operations correctly. It’s crucial to handle these operations properly to catch any exceptions that might occur. To help with this, I've written an extension code for managing Async/Await within a single thread.
Here, you see how to write a helper class for this purpose.
/// <summary> /// It helps to perform asynchronous actions in revit, because Async does not work in revit /// </summary> public static class AsyncTasksExecutor { public static T Execute<T>(Func<Task<T>> action) { var task = Task.Run(action.Invoke); return task.GetAwaiter().GetResult(); } public static T Execute<T>(Func<ValueTask<T>> action) { var task = Task.Run(async() => await action()); return task.GetAwaiter().GetResult(); } }
Here I provide an example of how to use this helper class in your projects.
public void ShowHowExtensionWorks() { object yourObject = new object(); bool result = AsyncTasksExecutor.Execute(() => DoAsyncWorks(yourObject)); } public async Task<bool> DoAsyncWorks(object someObjectsYouCanUse) { await Task.Delay(1000);//Simulate async operation return true; }
I would love to hear your thoughts—if you've had experience working with asynchronous calls in the Revit API, please share your insights in info@apibim.com.