Skip to content

Instantly share code, notes, and snippets.

@ricaun
Created July 24, 2024 14:07
Show Gist options
  • Save ricaun/7c7fcabb4cb320f9e69a3917e8e24d90 to your computer and use it in GitHub Desktop.
Save ricaun/7c7fcabb4cb320f9e69a3917e8e24d90 to your computer and use it in GitHub Desktop.
Simple Async ExternalEventHandler for Revit API
using Autodesk.Revit.UI;
using System;
using System.Threading.Tasks;
public class AsyncExternalEventHandler : IExternalEventHandler
{
private readonly Action<UIApplication> execute;
private readonly ExternalEvent externalEvent;
private TaskCompletionSource<bool> eventCompleted;
public AsyncExternalEventHandler(Action<UIApplication> execute)
{
this.execute = execute;
this.externalEvent = ExternalEvent.Create(this);
}
public Task RaiseAsync()
{
eventCompleted = new TaskCompletionSource<bool>();
externalEvent.Raise();
return eventCompleted.Task;
}
public void Execute(UIApplication app)
{
try
{
execute.Invoke(app);
eventCompleted.TrySetResult(true);
}
catch (Exception ex)
{
eventCompleted.TrySetException(ex);
}
}
public string GetName()
{
return this.GetType().Name;
}
}
@ricaun
Copy link
Author

ricaun commented Jul 24, 2024

This command show the title of the document two times after a second wait.

AsyncExternalEventHandler need to be created inside the Revit API Context

using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using System.Threading.Tasks;

[Transaction(TransactionMode.Manual)]
public class CommandAsync : IExternalCommand
{
    public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elementSet)
    {
        UIApplication uiapp = commandData.Application;

        var showTitleHandler = new AsyncExternalEventHandler(ShowTitle);

        Task.Run(async () =>
        {
            await Task.Delay(1000);
            await showTitleHandler.RaiseAsync();
            await Task.Delay(1000);
            await showTitleHandler.RaiseAsync();
        });

        return Result.Succeeded;
    }

    public static void ShowTitle(UIApplication app)
    {
        Document document = app.ActiveUIDocument.Document;
        TaskDialog.Show("Title", document.Title);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment