c# - 基本任务使用
问题描述
如果播放器的当前位置没有花(“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");
}
}
}
}
解决方案
推荐阅读
- javascript - 如何避免未使用的 setState 函数?可以在没有 setter 的情况下创建 React useState 吗?
- python-3.x - 如何从 TimeStampedModel 显示在管理面板中创建
- javascript - 我尝试映射我映射但无法到达的数组的内容(未定义为 no-undef)
- node.js - 续集 Nodejs-Express API 中的正文解析器错误
- sql - 根据重叠时段对数据进行分组或求和
- node.js - 如何在 Electron 应用程序上正确存储 Google Drive API 的客户端密码?
- flask - 使用 GStreamer 的 Flask Live HLS 流式处理仅适用于本地计算机
- powerbi - 如何将日期表(日期类型列)连接到事实表日期(日期时间类型列)类型?
- python - Python:在另一个函数中定义一个函数
- r - 根据条件更改列的值(缺失数据和分类)