简体   繁体   中英

StackOverflowException was unhandled in backgroundworker function

I want to background worker that works continuously. But i'm getting error "StackOverflowException was unhandled" how can i fix it ? Or is there a different way ? I'm so sorry my bad English..

private void Form1_Load(object sender, EventArgs e)
    {
       workerMesaj.RunWorkerAsync();
    }


private void workerMesaj_DoWork(object sender, DoWorkEventArgs e)
     {
        /*
           ... some codes
        */

        System.Threading.Thread.Sleep(100);
        workerMesaj_DoWork(sender,e)          //i'm trying create loop forever with this code. 
     }

//i'm trying create loop forever with this code.

You are creating unbound recursion which creates stack frame on each workerMesaj_DoWork . Eventually your stack is exhausted and you have that exception. If you want forever loop you should use loop - not recursion.

Do not initiate the worker thread from inside itself otherwise it is never able to dispose properly because the parent is hosting another child and cannot dispose until the child is disposed. This continues on this way forever thus causing the overflow.

Instead create you loop INSIDE the worker thread by creating a while loop like this;

private void workerMesaj_DoWork(object sender, DoWorkEventArgs e)
     {
        bool RunWorker=true;
        while(RunWorker)
        {
        /*
           ... some codes
        */
        }
     }

Additionally research what you plan to do a little more because odds are they may be an event triggerable solution and if this is the case then it is a much cleaner way to create a listener or constant worker.

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