简体   繁体   中英

C# - Backgroundworker and REST service

I have a webservice that call a class with backgroundworker and when i return a status 200, i receive this exception in my REST client:

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

I've implemented my service this way:

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

And here is my class with 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");

    }
}

What's wrong with this implementation?

Thanks

Your Execute method will return immediately after starting the BackgroundWorker (rather than waiting until GenerateContent and GenerationCompleted have run). So your service will return an HTTP 200 result to the client while GenerateContent is still working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM