Navid Navid - 17 days ago 5
C# Question

Having Time Delay in C#

This code is an algorithm search and goal is when table is ordered from 1 to 16 (in first of game table is not ordered) . I want to have a delay when it fills UI Table (The table that show result of the game in UI), because i want to show the player the process of solving game by algorithm.
How can i have delay (1 or 2 seconds) in

//Make Delay
?

public bool BFS_TreeSearch(int[,] table, Queue<int[,]> fringe)
{
MakeNode(table, fringe);

do
{
if (fringe.Count == 0)
return false;
int[,] node = fringe.Dequeue();

//Make Delay


FillTableUI(node);

if (isGoal(node))
return true;
MakeNode(node, fringe);
} while (true);

}

Answer

You can use a synchronous or an asynchronous sleep by using Thread.Sleep or Task.Delay based on your requirements. As you want to show some things on UI, I think you should use the latter like this. Note that this will force you to make your method async, so you have to call it differently.

public async Task<bool> BFS_TreeSearch(int[,] table, Queue<int[,]> fringe)
{
    MakeNode(table, fringe);

    do
    {
        if (fringe.Count == 0)
            return false;
        int[,] node = fringe.Dequeue();

        await Task.Delay(2000) // continue from here after 2 seconds


        FillTableUI(node);

        if (isGoal(node))
            return true;
        MakeNode(node, fringe);
    } while (true);

}

See this post also in this topic.

Comments