C# - Backgroundworker和REST服务

时间:2014-05-20 16:32:26

标签: c# rest asynchronous backgroundworker

我有一个使用backgroundworker调用类的web服务,当我返回状态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);          
    }

这是我的班级背景工作者:

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

    }
}

这种实施有什么问题?

由于

1 个答案:

答案 0 :(得分:0)

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