Basic Task using

75 views Asked by At

I try to place a string ("-") if there is no flower ("X") in the current location of the player. In the same time while I'm placeing "-" I need to start a Task. This should changes the "-" for an other State in every seconds. The Task should finish when we get the end of the collection (string[]). So each flower has a Task, and also a CancellationToken (I need to check whether there is a cancellation). But nothing happen when I Start the task.

public class Flower
{
    public int FlowerX { get; set; }
    public int FlowerY { get; set; }
    public string[] States { get; set; }
    public string CurrentState { get; set; }
    public Task FlowerTask { get; set; }
    public CancellationToken FlowerCt { get; set; }

    public Flower()
    {

    }
    public Flower(int flowerX, int flowerY, string currentState)
    {
        FlowerX = flowerX;
        FlowerY = flowerY;
        CurrentState = currentState;
    }

    public Flower(int flowerX, int flowerY)
    {
        FlowerX = flowerX;
        FlowerY = flowerY;
        States = new string[] { "-", "+", "w", "W", "o", "O", "X" };
    }
}
public class Garden
{
    public int PlayerX { get; set; }
    public int PlayerY { get; set; }
    public List<Flower> Flowers { get; set; }
    public int Length { get; private set; }
    public int Width { get; private set; }

    public Garden(int lenght, int width)
    {
        Flowers = new List<Flower>();
        Length = lenght;
        Width = width;
    }



    public void PlantFlower()
    {
        foreach (var flower in Flowers)
        {
            if (PlayerX != flower.FlowerX && PlayerY != flower.FlowerY)
            {
                Flowers.Add(new Flower(PlayerX, PlayerY));
            }

            if (PlayerX == flower.FlowerX && PlayerY == flower.FlowerY && flower.CurrentState != "X")
            {
                Flower flowerObject = new Flower(PlayerX, PlayerY, "-");
                Flowers.Add(new Flower
                {
                    CurrentState = "-",
                    FlowerX = PlayerX,
                    FlowerY = PlayerY,
                });

                int i = 0;
                do
                {
                    flowerObject.FlowerTask = Task.Run(() =>
                    {
                        Thread.Sleep(1000);
                        flowerObject.FlowerCt.ThrowIfCancellationRequested();
                        try
                        {
                            flower.CurrentState = flowerObject.States[i];
                            i++;
                            //flower.SCounter++;
                        }
                        catch (OperationCanceledException)
                        {
                            return;
                        }
                    });
                } while (i < flower.States.Length || flower.CurrentState == "X");
            }
        }
    }
}
0

There are 0 answers