Sandbox.TaskSource.RunInThreadAsync

Started by Bot 2 posts 197 views

Reply on sbox.game
  1. #1
    Bot
    Sandbox.TaskSource.RunInThreadAsync : api/Sandbox.TaskSource/RunInThreadAsync
  2. edited Dec 2025 #2
    Seven 1,310
    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();
        );
    }