gpt4 book ai didi

c# - 取消路线内的任务

转载 作者:行者123 更新时间:2023-11-30 17:36:48 26 4
gpt4 key购买 nike

我正在使用 Nancy API 构建 C# 应用程序。我有一个异步操作,它运行一个非常长的优化算法,有时需要被用户取消。伪代码如下:

        Get["/algorithm/run/", true] = async (parameters, ct) =>
{
var algy = new Algorithm();
var result = await Task.Run(() => algy.RunAlgorithm(ct), ct);
};

如何取消 CancellationToken (ct),或者创建一个新的算法取消方法?

我尝试过的替代方法是:

var cts = new CancellationTokenSource();     
var cToken = cts.Token;

Get["/algorithm/run/", true] = async (parameters, ct) =>
{
var algy = new Algorithm();
var result = await Task.Run(() => algy.RunAlgorithm(cToken), cToken);
};


Get["/schedule/stop"] = _ =>
{
cts.Cancel();
};

但这显然行不通,因为路由在它自己的异步任务中。

我已阅读此处发布的文章:http://blog.jonathanchannon.com/2013/08/24/async-route-handling-with-nancy/其中提到:

The CancellationToken is passed in so you can check the ct.IsCancellationRequested property to determine if you want to cooperatively cancel processing in your route handler. This property may be set for example if there is an internal error or if a piece of middleware decides to cancel the request, or the host is shutting down. If you didn't know Nancy is OWIN compliant and has been pretty much since the OWIN specification came out.

任何帮助将不胜感激,因为我是处理线程的新手。

完整示例:

using Nancy;
using Nancy.Hosting.Self;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace NancyApp
{
class Program
{
private static NancyHost NancyHost { get; set; }
private static HttpClient Client { get; set; }

static void Main(string[] args)
{
var configuration = new HostConfiguration()
{
UrlReservations = new UrlReservations() { CreateAutomatically = true }
};

NancyHost = new NancyHost(configuration, new Uri("http://localhost:1234"));

NancyHost.Start();

Client = new HttpClient();
Client.Timeout = new TimeSpan(1, 0, 0);
Client.BaseAddress = new Uri("http://localhost:1234");

Console.WriteLine("Hosting...\n");

Client.GetAsync("http://localhost:1234/run");
System.Threading.Thread.Sleep(5000);
Client.GetAsync("http://localhost:1234/cancel");
Console.ReadLine();
}
}

public class TestModule : NancyModule
{
CancellationTokenSource cts = new CancellationTokenSource();

public TestModule()
{
Get["/run", true] = async (parameters, ct) =>
{
Algorithm ag = new Algorithm();
Console.Write("Running Algorithm...\n");
var result = await Task.Run(() => ag.RunAlgorithm(cts.Token), cts.Token);

return Response.AsText(result.ToString());
};

Get["/cancel"] = _ =>
{
Console.Write("Cancel requested recieved\n");
cts.Cancel();
return Response.AsText("Foo");
};

}
}

class Algorithm
{
public Algorithm()
{

}

public int RunAlgorithm(CancellationToken cToken)
{
int min = Int32.MinValue;

while (min < Int32.MaxValue)
{
if (!cToken.IsCancellationRequested)
{
min++;
}
else
{
Console.Write("IsCancellationRequested true!\n");
cToken.ThrowIfCancellationRequested();
}
}
return min;
}
}
}

最佳答案

工作更正:

public class TestModule : NancyModule
{
static CancellationTokenSource cts = new CancellationTokenSource();
static CancellationToken cToken = cts.Token;

public TestModule()
{
Get["/run", true] = async (parameters, ct) =>
{
Algorithm ag = new Algorithm();
Console.Write("Running Algorithm...\n");
var result = await Task.Run(() => ag.RunAlgorithm(cToken), cToken);

return Response.AsText(result.ToString());
};

Get["/cancel"] = _ =>
{
Console.Write("Cancel requested recieved\n");
cts.Cancel();
cts.Dispose();
cts = new CancellationTokenSource();
cToken = cts.Token;
return Response.AsText("Cancelled!");
};
}
}

感谢@Peter Duniho 的协助。

关于c# - 取消路线内的任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38949850/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com