c# -后台工作者和REST服务

本文关键字:REST 服务 工作者 后台 | 更新日期: 2023-09-27 18:04:11

我有一个webservice调用一个类与backgroundworker,当我返回一个状态200,我收到这个异常在我的REST客户端:

An asynchronous module or handler completed while an asynchronous operation was still pending.

我是这样实现我的服务的:

    [Route("/service")]
    [HttpPost]
    public HttpResponseMessage generate(String value)
    {           
        Service service = new Service();
        service.Execute();
        return Request.CreateResponse(HttpStatusCode.OK);          
    }

这是我的类backgroundworker:

public class Service
{
    private BackgroundWorker worker = new BackgroundWorker();

    public void Execute(Client client)
    {
        worker = new BackgroundWorker
        {
            WorkerReportsProgress = true,
            WorkerSupportsCancellation = true
        };
        worker.DoWork += (obj, e) => GenerateContent(client);
        worker.RunWorkerCompleted += (obj, e) => GenerationCompleted(client.Token);

        worker.RunWorkerAsync();
    }
    private void GenerateContent(Client client)
    {
       //doStuff
    }

    private void GenerationCompleted(String token)
    {
        // TODO 
        Console.WriteLine("Finished");
    }
}

这个实现有什么问题?

谢谢

c# -后台工作者和REST服务

您的Execute方法将在启动BackgroundWorker后立即返回(而不是等到GenerateContentGenerationCompleted运行)。因此,当GenerateContent仍然工作时,您的服务将返回一个HTTP 200结果给客户端。