首页 > 解决方案 > 基本任务使用

问题描述

如果播放器的当前位置没有花(“X”),我会尝试放置一个字符串(“-”)。在我放置“-”的同时,我需要启动一个任务。这应该每秒钟改变另一个状态的“-”。当我们得到集合的结尾(字符串 [])时,任务应该完成。所以每朵花都有一个Task,还有一个CancellationToken(我需要检查是否有cancel)。但是当我开始任务时没有任何反应。

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");
            }
        }
    }
}

标签: c#task

解决方案


推荐阅读