Skip to content

EN CSharp Concurrency

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

Threads, tasks and synchronization

Manual C# · Examples UO

Asynchrony allows you to wait, concurrency allows you to serve several jobs, parallelism allows you to perform them simultaneously. Task.Run suitable for computational work; by itself it does not make game objects thread safe. UI and the game world must be served by the provided API host.

Simple example (Example.cs)

Save this example separately as Example.cs. Run it independently of the other examples on this page.

Example.cs:

// PROJECT-EXAMPLE
int count = 0;
System.Threading.Tasks.Parallel.For(0, 3, _ => System.Threading.Interlocked.Increment(ref count));
System.Console.WriteLine(count);

Result:

3
int total = await Task.Run(() => Enumerable.Range(1, 100).Sum(), Cancellation);
UO.Print(total.ToString());
using System.Collections.Concurrent;
var values = new ConcurrentDictionary<string, int>();
values.TryAdd("items", 1);
values.AddOrUpdate("items", 1, (_, old) => old + 1);
UO.Print(values["items"].ToString());

lock protects the synchronous section, SemaphoreSlim.WaitAsync - asynchronous wait for access, Interlocked - individual atomic operations. Don't hold a lock during long external work and don't run forgotten tasks accessing the session after the script has completed.

Official documentation: Threads, tasks and synchronization - Microsoft Learn.

Clone this wiki locally