Search code examples
c#multithreadingasync-awaitchess

Making a separated thread for a long-running task


I'm working on my little chess engine in C#, and I want to make my search function run in the background. (so that the UI is still interactable) I checked some other stackoverflow solutions talking about the async and await keywords (also about Task.Run()). But I'm at the beginner level. I could not understand what was going on, and I could not make it work for my code.

Here's my sample code:

public static Move GetMove()
{
    // This function is called every frame if it is the engine's turn
    // Your solution goes here
}

engine.StartSearch() function starts a search, and it will probably take some time to finish. You can grab the result(Move) by calling engine.GetMove() after a search.

How can I make a background task for the search, and how do I make it wait for the result?

I have tried using async and await keywords but I don't understand how it works..


Solution

  • you can make a thread and make it background thread but you should join your background thread to your main thread by calling thread.join() and it will be up and run until main thread finish their work

        public static void GetMove(Action<Move> callback)
        {
            Thread thread = new Thread(() =>
            {
                Move bestMove = SearchBestMove();
                callback(bestMove);
            });
    
            thread.IsBackground = true;
            thread.Start();
        }
    
        private static Move SearchBestMove()
        {
            // Implement your chess engine's search logic here
            // This is a long-running operation that should run in the background
    
            Move bestMove = new Move();
            // Perform the search to find the best move
            // ...
    
            return bestMove;
        }
    

    or make it easier and using Task approach and calling Task.Run , Acctually it using thread pool threads and they are Background threads by dafault

            public static async Task<Move> GetMoveAsync()
            {
                // Use Task.Run to run the search function in the background
                Move bestMove = await Task.Run(() => SearchBestMove());
                return bestMove;
            }
        
            private static Move SearchBestMove()
            {
                // Implement your chess engine's search logic here
                // This is a long-running operation that should run in the background
        
                Move bestMove = new Move();
                // Perform the search to find the best move
                // ...
        
                return bestMove;
            }