swiftlys2/docs/api/releases/features/ai/

Thread Safety

Some framework APIs are thread-unsafe. Calling them from a non-main-thread context (e.g. inside Task.Run, or after await-ing a database call) is not supported and can cause undefined behavior or crashes.

If an API is marked thread-unsafe, don't call it directly from a background thread. Use its Async counterpart, or schedule the call back onto the main thread first.

Core Rule

Thread-unsafe methods either carry APIThreadUnsafeAttribute ([ThreadUnsafe]) or say so in their XML comments - APIIEngineService.DispatchParticleEffect is one of the latter - and must run on the game thread. Prefer their Async variant when one exists - it takes care of the dispatch for you; otherwise hand the call to Core.Scheduler yourself. Check Core.IsGameThread at runtime to branch explicitly:

if (!Core.IsGameThread)
{
    Core.Scheduler.NextTick(() => player.SendChat("Hello!"));
}
else
{
    player.SendChat("Hello!");
}

Dispatching to the Main Thread

The *Async counterparts listed further down already dispatch for you, so an async flow can call them directly. Everything else goes through APIISchedulerService (APIISwiftlyCore.Scheduler), which has four ways to hand a call back to the game thread:

MethodBehavior
APIISchedulerService.NextTickRuns the callback on the next server tick
APIISchedulerService.NextWorldUpdateRuns the callback on the next world update phase instead
APIISchedulerService.NextTickAsyncSame as NextTick, but awaitable and able to return a value
APIISchedulerService.NextWorldUpdateAsyncSame as NextWorldUpdate, but awaitable and able to return a value

The awaitable variants take either an Action (returning Task) or a Func<T> (returning Task<T>):

int computedValue = await Core.Scheduler.NextTickAsync(() => 42);

Don't pass an async callback (Func<Task>/Func<Task<T>>) to NextTick, NextWorldUpdate or their awaitable variants - those overloads are [Obsolete] and throw InvalidOperationException, since an async callback isn't guaranteed to resume on the game thread. Use the plain Action/Func<T> overloads instead.

The same service also has timer APIs (Delay, Repeat, DelayAndRepeat, AddTimer, ...) for work that is periodic rather than one-off - see Scheduler.

Safe Usage Patterns

Prefer Async counterparts in any async flow (e.g. after a database call):

public async Task NotifyPlayerAsync(IPlayer player)
{
    await player.SendChatAsync("Hello from an async flow.");
 
    using var sound = new SoundEvent("UI.CounterBeep", volume: 1.0f, pitch: 1.0f);
    sound.Recipients.AddAllPlayers();
    await sound.EmitAsync();
}

For anything else - a thread-unsafe API without an Async variant, or arbitrary code that has to run on the game thread - schedule it explicitly instead:

await Core.Scheduler.NextTickAsync(() => player.SendChat("Executed on the main thread via the scheduler."));

Common Thread-Unsafe APIs

Thread-Unsafe APIAsync Alternative
APIIPlayer.SendChatSendChatAsync
APIIPlayer.SendMessageSendMessageAsync
APIIPlayer.SendConsoleSendConsoleAsync
APIIPlayer.SendCenterSendCenterAsync
APIIPlayer.SendAlertSendAlertAsync
APIIPlayer.SendCenterHTMLSendCenterHTMLAsync
APIIPlayer.SendChatEOTSendChatEOTAsync
APIIPlayer.SendNotifySendNotifyAsync
APIIPlayer.KickKickAsync
APIIPlayer.ExecuteCommandExecuteCommandAsync
APIIPlayer.TeleportTeleportAsync
APIIPlayer.TakeDamageTakeDamageAsync
APIIPlayer.SwitchTeam / ChangeTeamSwitchTeamAsync / ChangeTeamAsync
APIIPlayer.GetLoadoutItemNone - dispatch it with Core.Scheduler
IPlayerManager.SendMessage and friendsThe matching *Async methods, e.g. SendChatAsync, SendCenterAsync and SendNotifyAsync (server-wide)
APISoundEvent.EmitEmitAsync
APIIGameEventService.Fire and friendsFireAsync, FireToPlayerAsync, FireToServerAsync
APIIGameService.EmitHEGrenade and friendsEmitHEGrenadeAsync, EmitFlashbangAsync, EmitSmokeGrenadeAsync, EmitMolotovAsync, EmitDecoyAsync

APIIEngineService.DispatchParticleEffect is documented as thread-unsafe and has a DispatchParticleEffectAsync counterpart, and APIIEngineService.ExecuteCommand has an ExecuteCommandAsync variant - use those from a background flow.

Checklist

Find sync calls to thread-unsafe APIs running after an await (outside Load/event handlers), replace with the Async variant, or wrap with Core.Scheduler.NextTick/NextWorldUpdate (or their awaitable variants) if no Async variant exists. Don't fire-and-forget gameplay-critical calls - await them or handle failures explicitly.

Reference

See Swiftly Core for Core.IsGameThread and Core.Scheduler.

See Scheduler for the full scheduling API.