Repository navigation
Writing Modules
Алексей . edited this page Mar 21, 2026
·
6 revisions
using Microsoft.Extensions.Logging;
using SFSharp;
[SFModule("my-module", "MyModule", Description = "Does something useful", Order = 100)]
public sealed class MyModule : SFModuleBase
{
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
Log.LogInformation("started");
while (!cancellationToken.IsCancellationRequested)
{
using (ModuleLoopScope _ = Context.TrackLoop("tick"))
{
Context.Heartbeat("running");
// Your work here
}
await Task.Yield();
}
}
}Register in Program.cs:
container.RegisterModule<MyModule>();Important: Always place
await Task.Yield()outside theusingblock. TheModuleLoopScopemeasures synchronous work time only. Including the yield inside the scope inflates the load metric.
// CORRECT — yield outside scope
while (!cancellationToken.IsCancellationRequested)
{
using (ModuleLoopScope _ = Context.TrackLoop("poll"))
{
// synchronous work measured here
}
await Task.Yield(); // cooperative scheduling
}
// WRONG — yield inside scope, load will be ~80-100%
while (!cancellationToken.IsCancellationRequested)
{
using ModuleLoopScope _ = Context.TrackLoop("poll");
// work
await Task.Yield(); // scope includes wait time!
}protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
// Auto-disposed when module stops, auto-tracked in telemetry
using IDisposable cmd = Context.RegisterChatCommand("mycmd", OnCommand);
while (!cancellationToken.IsCancellationRequested)
{
// ...
await Task.Yield();
}
}
private void OnCommand(string? args)
{
// args is null if user typed "/mycmd", otherwise the full argument string
SF.Chat.Add($"You said: {args ?? "(nothing)"}");
}using (ModuleLoopScope _ = Context.TrackLoop("keyboard"))
{
if (SF.Keyboard.IsKeyPressed(VK.F5))
{
Context.IncrementCounter("f5.pressed");
await DoSomething();
}
Context.Heartbeat("watching keys");
}
await Task.Yield();For modules that react to chat messages, use async streams instead of polling:
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
await foreach (var entry in SF.Chat.StreamChatEntries(cancellationToken))
{
Context.IncrementCounter("chat.entries");
if (entry.Text?.Contains("keyword") == true)
{
Context.Heartbeat("match-found");
// process
}
}
}For server-side messages (colored by server):
await foreach (var entry in SF.Chat.StreamServerChatEntries(cancellationToken))
{
if (entry.Kind == ServerChatKind.ClientMessage)
{
// player chat message
}
}protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
// Subscribe to incoming RPC
using IDisposable sub = Context.RegisterDisposable(
SF.Rpc.Subscribe(RpcId.Chat, OnChatRpc));
// Subscribe to incoming packets
using IDisposable pktSub = Context.RegisterDisposable(
SF.Packets.SubscribeIncoming(PacketId.ArizonaCef, OnArizonaPacket));
while (!cancellationToken.IsCancellationRequested)
{
using (ModuleLoopScope _ = Context.TrackLoop("idle"))
{
Context.Heartbeat("waiting events");
}
await Task.Yield();
}
}
private void OnChatRpc(IncomingRpcArgs args)
{
BitStreamReader reader = args.CreateReader();
// parse RPC data
}
private void OnArizonaPacket(IncomingPacketArgs args)
{
BitStreamReader reader = args.CreateReader();
reader.SkipBytes(1); // skip packet ID byte
int subId = ArizonaPacket.ReadSubId220(ref reader);
// parse Arizona packet
}// Message dialog (OK/Cancel)
SFDialogButton result = await SF.Dialog.ShowMessage("Title", "Body text");
if (result == SFDialogButton.OK) { /* confirmed */ }
// List dialog
var listResult = await SF.Dialog.ShowList(
"Title",
new[] { "Item 1\tValue 1", "Item 2\tValue 2" },
"Header Col1\tHeader Col2"
);
if (listResult.Button == SFDialogButton.OK)
{
int selected = listResult.SelectedIndex;
}
// Input dialog
var inputResult = await SF.Dialog.ShowInput("Title", "Enter value:");
if (inputResult.Button == SFDialogButton.OK)
{
string text = inputResult.Text;
}// Counters — numeric, increment-only, visible in /sfs info
Context.IncrementCounter("requests.total");
Context.IncrementCounter("bytes.received", byteCount);
// Details — key-value pairs, visible in /sfs info
Context.SetDetail("status", "processing");
Context.SetDetail("target", playerId.ToString());
Context.SetDetail("status", null); // remove detailUse SF.UserFilesDirectory for persistent storage:
string path = Path.Combine(SF.UserFilesDirectory, "my-module-data.json");
File.WriteAllText(path, json);Override CreateLogger to use a third-party provider (Serilog, NLog, etc.):
protected override ILogger CreateLogger(ModuleContext context)
{
// Default: SFLoggerProvider writes to sf_arz.log via background thread
// Override for custom logging:
return myLoggerFactory.CreateLogger(context.Descriptor.Id);
}protected override Task OnStartingAsync()
{
Log.LogInformation("Allocating resources...");
return Task.CompletedTask;
}
protected override Task OnFaultedAsync(Exception ex)
{
Log.LogError(ex, "Module crashed");
return Task.CompletedTask;
}
protected override Task OnStoppedAsync()
{
Log.LogInformation("Goodbye");
return Task.CompletedTask;
}// Switch to main thread (for game API calls)
await Context.SwitchToMainThreadAsync();
// Run work on background thread
await Context.RunBackground(async () =>
{
// heavy I/O, network, etc.
var data = await httpClient.GetStringAsync(url);
});using Microsoft.Extensions.Logging;
using SFSharp;
[SFModule("key-counter", "KeyCounter",
Category = "Utility",
Description = "Counts F5 presses and shows total in chat",
ExecutionModel = ModuleExecutionModel.MainThread,
RestartPolicy = ModuleRestartPolicy.OnFault,
Order = 100)]
public sealed class KeyCounterModule : SFModuleBase
{
private int _count;
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
using IDisposable cmd = Context.RegisterChatCommand("keycount", _ =>
{
SF.Chat.Add($"F5 pressed {_count} times");
});
Context.SetDetail("key", "F5");
while (!cancellationToken.IsCancellationRequested)
{
using (ModuleLoopScope _ = Context.TrackLoop("poll"))
{
if (SF.Keyboard.IsKeyPressed(VK.F5))
{
_count++;
Context.IncrementCounter("f5.total");
Context.Heartbeat("key-pressed");
Log.LogInformation("F5 pressed, total={Count}", _count);
SFColor accent = SFColors.Cyan | SFColors.Blue;
SF.Chat.Add(accent.Apply($"F5 count: {_count}"));
}
}
await Task.Yield();
}
}
}- Главная / Home
- Установка
- Архитектура и совместимость
- SA-MP R1, R3-1, R5-1
- Написание модулей
- Плагины и зависимости
- Жизненный цикл
- API модулей
- Потоки и время жизни
- Ранняя загрузка
- Конфигурация и ассеты