trophy 0
May 2025 109 posts
Sandbox.TaskSource.RunInThreadAsync : api/Sandbox.TaskSource/RunInThreadAsync
trophy 820
May 2023 32 posts
Seven 25 days ago edited 12 days ago
Runs a function on a worker thread and returns its result.
 
Overload 1
"Complete this function on a worker thread"
async Task GenericAsync() // Whatever async code your writing
{
    await ts.RunInThreadAsync( DoHeavyWork );
}

private void DoHeavyWork()
{
	// CPU-bound or blocking work
	ExpensiveCalculation();
}


Overload 2
 “return the value from this function that is completed on worker thread” 
async Task GenericAsync() // Whatever async code your writing
{
    await ts.RunInThreadAsync( ComputeSomethingLarge );
}

private int ComputeSomethingLarge()
{
    return ExpensiveCalculation(10000);
}

Overload 3
 "I need to await things while I complete this async pipeline"
async Task GenericAsync() // Whatever async code your writing
{
    await ts.RunInThreadAsync( LoadAndParseAsync );
}

private async Task LoadAndParseAsync()
{
	await LoadFileAsync();
	await ParseAsync();
}

Overload 4
 “I need to produce a value from an awaited async pipeline” 
async Task GenericAsync() // Whatever async code your writing
{
    ParsedData data = await ts.RunInThreadAsync( LoadAndParseDataAsync );
}

private async Task<ParsedData> LoadAndParseDataAsync()
{
	string json = await LoadJsonAsync();
	return ParseData( json );
}


these also work the anonymous functions but those examples were harder to parse quickly

example of using anonymous function for Overload 1
async Task GenericAsync() // Whatever async code your writing
{
    await ts.RunInThreadAsync( () =>
        ExpensiveCalculation();
    );
}
people
Log in to reply
You can't reply if you're not logged in. That would be crazy.