简体   繁体   中英

How to invoke a delegate call as Fire-And-Forget

I have a .NET Standard library that is able to report back its progress. I would like the program not to block until the progress reporting method has completed. Instead I would like a Fire-And-Forget pattern where the work can continue inside DoWork()

class Foo
{
   public delegate void ProgressEvent(double progress, double max);
   public ProgressEvent ReportProgress { get; set; }

   public void DoSomeWork()
   {
      for(int i = 0; i < 1000; i ++)
      {
         // Do work
         ReportProgress?.Invoke(i, 1000);   // I do not want to wait for the method to return here
      }
   }
}

So far, I have put it as a requirement that the method body assigned to ReportProgress must execute quickly. But if there is a good coding solution, I would not like to rely on requirements.

There is the possibility to wrap the invocation of ReportProgress in a new thread, but that seems inefficient - that will spawn 1000 threads.

This question suggests that I should somehow expose a ThreadPool in my class, but I am not sure that this makes sense: Simplest way to do a fire and forget method in C#?

How would you approach this situation?

EDIT: I belive that the user of the class is using it like this. Note that there is a potential slow update of a remote database. This customer was the reason I needed to rethink the struture.

void HandleRequest(int requestID)
{
    
    Thread workerThread = new Thread(()=>
    {
        double currentProgress = 0;
        Foo f = new Foo();
        f.ReportProgress = (progress, max) =>
        {
            double newProgress = progress/max;
            if(newProgress > currentProgress)
            {
                currentProgress = newProgress;
                UpdateRemoteDataBase(currentProgress, requestID);
            }
        }
        t.DoWork();
    });
}

How about just wrap your DoSomework with Thread

 class Foo
    {
        public delegate void ProgressEvent(double progress, double max);
        public ProgressEvent ReportProgress { get; set; }

        public void DoSomeWork()
        {
            Thread workerThread = new Thread(() =>
            {
                for (int i = 0; i < 1000; i++)
                {
                    // Do work
                    Thread.Sleep(1000);
                    ReportProgress?.Invoke(i, 1000);   // I do not want to wait for the method to return here
                }
            });
            workerThread.Start();
            return;
        }
    }

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