Repository navigation
EN CSharp Concurrency
Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어
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.
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.
ClassicUO — Bad Newbie & C# Scripts IDE