0

I want to pass somehow delegate to Task, which has to execute some code on variable (AutoResetEvent) inside this task when requested. Below is pseudo code:

var task = Task.Run(() => DoSth()); + delegate somehow

public async Task DoSth()
{
   public static AutoResetEvent waitEvent = new AutoResetEvent(true);
   while(true)
   {
       ...
       waitEvent.WaitOne(seconds * 1000);
   {
}

What this delegate has to do is:

waitEvent.Set();

because I do not want wait 60 seconds.

And at some point tell task to run delegate code.

gorrch
  • 521
  • 3
  • 16
  • 1
    It's not a good idea to mix thread primitives (like AutoResetEvent) with the task programming model... – Sean Aug 22 '19 at 15:26
  • It's not really clear what you're trying to do. Can you update your question to explain what problem you're actually trying to solve? There's a good chance that there's a better pattern to use than passing a delegate, such as using a CancellationToken or passing a task and awaiting `Task.WhenAny()`. – StriplingWarrior Aug 22 '19 at 16:13

1 Answers1

-1

You should not start a task and then block waiting for something else. This will cause the ThreadPool to suffer from one useless thread and can cause ThreadStarvation in the end.

You should start a new dedicated thread and use a shared variable to trigger your work.

new Thread(DoSth).Start();

private readonly object protect = new object();

public async Task DoSth()
{
   public static AutoResetEvent waitEvent = new AutoResetEvent(true);
   while(true)
   {
       bool triggered = false;
       lock(protect)
       {
           Monitor.Wait(protect, seconds * 1000);
           triggered = shouldWork;
           shouldWork = false;
       }

       if(triggered) 
           Work();
  }
}

public void Trigger()
{
    lock(protect)
    {
        shouldwork = true;
        Monitor.Pulse(protect);//will end the wait on the other thread
    }
}
Bruno Belmondo
  • 2,299
  • 8
  • 18
  • I have many threads/tasks and that is why I can not use one shared variable. Despite this we will lose reference to this object. – gorrch Aug 22 '19 at 17:20