有这样的代码,怎么能简化?我在c#中有一个取消任务的问题,task[0]不会停止执行。代码如下:
cts1 = new CancellationTokenSource();
cts2 = new CancellationTokenSource();
cts3 = new CancellationTokenSource();
cts4 = new CancellationTokenSource();
cts5 = new CancellationTokenSource();
cts6 = new CancellationTokenSource();
cts7 = new CancellationTokenSource();
cts8 = new CancellationTokenSource();
Task _cockroach1 = SetSpeed(cockroach1, 1);
Task _cockroach2 = SetSpeed(cockroach2, 2);
Task _cockroach3 = SetSpeed(cockroach3, 3);
Task _cockroach4 = SetSpeed(cockroach4, 4);
Task _cockroach5 = SetSpeed(cockroach5, 5);
Task _cockroach6 = SetSpeed(cockroach6, 6);
Task _cockroach7 = SetSpeed(cockroach7, 7);
Task _cockroach8 = SetSpeed(cockroach8, 8);
private async Task SetSpeed(Image _cockroach, int _number)
{
while (_x <= 830)
{
if (_number == 1 && cts1.Token.IsCancellationRequested) return; //остановка таска
if (_number == 2 && cts2.Token.IsCancellationRequested) return;
if (_number == 3 && cts3.Token.IsCancellationRequested) return;
if (_number == 4 && cts4.Token.IsCancellationRequested) return;
if (_number == 5 && cts5.Token.IsCancellationRequested) return;
if (_number == 6 && cts6.Token.IsCancellationRequested) return;
if (_number == 7 && cts7.Token.IsCancellationRequested) return;
if (_number == 8 && cts8.Token.IsCancellationRequested) return;
如何停止任务不是很清楚。
与其使用9个变量,为什么不将所有元素存储到数组或列表中呢?
var cts = Enumerable.Range(0, 9).Select(x => new CancellationTokenSource()).ToArray();
var cockroach = Enumerable.Range(0, 9).Select(x => new CockRoach(...)).ToArray();
var _cockroaches = cts.Select((x, i) => SetSpeed(cockroach[i], i);
private async Task SetSpeed(Image _cockroach, int _number)
{
while (_x <= 830)
{
if (cts[number].Token.IsCancellationRequested) return;
}
// ...
}
当你不喜欢linq语法时,你也可以使用老式的循环:
var cts = new CancellationTokenSource[9];
var cockroaches = new Image[9];
var _cockroaches = new Task[9];
for(int i = 0; i < 9; i++)
{
cts[i] = new CancellationTokenSource();
cockroaches[i] = new Image(...);
_cockroaches [i] = SetSpeed(cockroaches[i], i);
}