RedTShirtGaming
RedTShirtGaming
CC#
Created by RedTShirtGaming on 7/4/2024 in #help
async functions always finish on a background thread
Hello! I'm experienced with C#, but I'm just starting to learn about async functions and multithreading. I'm having an issue where a function that contains 'await Task.Run(...)' always finishes running on a background thread and not the main thread that it was called from. Here is my code
internal static async Task GenerateChunkAsync(Dictionary<Vector3Int, Chunk> chunks)
{
// Any main-thread setup here

var chunkData = await Task.Run(() =>
{
// Execute code on a background thread
var data = SomeFunc(5);
return data;
});

// Finish running on the main thread (important for opengl)
// For some reason, this always runs on the background thread that the Task.Run code was running on
Console.WriteLine($"Finished function in {chunkData}ms. Is main thread: {Engine.IsMainThread}");
}

private static long SomeFunc(int sleepTime)
{
var timer = new System.Diagnostics.Stopwatch();
timer.Start();

// Simulate some background work
Thread.Sleep(sleepTime * 1000);

timer.Stop();
return timer.ElapsedMilliseconds;
}
internal static async Task GenerateChunkAsync(Dictionary<Vector3Int, Chunk> chunks)
{
// Any main-thread setup here

var chunkData = await Task.Run(() =>
{
// Execute code on a background thread
var data = SomeFunc(5);
return data;
});

// Finish running on the main thread (important for opengl)
// For some reason, this always runs on the background thread that the Task.Run code was running on
Console.WriteLine($"Finished function in {chunkData}ms. Is main thread: {Engine.IsMainThread}");
}

private static long SomeFunc(int sleepTime)
{
var timer = new System.Diagnostics.Stopwatch();
timer.Start();

// Simulate some background work
Thread.Sleep(sleepTime * 1000);

timer.Stop();
return timer.ElapsedMilliseconds;
}
Is there a way of ensuring that the function that was called from the main thread always finishes running on the main thread? Thanks :D
60 replies