Regarding the event that some tasks cannot be processed in the task processing,

Asked 2 years ago, Updated 2 years ago, 98 views

Thank you for your help.
I would like to run a total of 10 tasks in the C# task.
When I debug, I run four or five tasks, but the rest of them don't run and I'm in a waiting state.
As a content, we are trying to run the same method repeatedly using one instance.
There should be no problem looking at the upper and lower limits of the thread pool, but
No reason or solution found.
Thank you for your cooperation.

I will write a brief source below.

// Where to generate 10 threads
TaskWork = new TaskWork();
 for(inti=0;i<10;i++){
    Task.Run(()=>taskWork.Work());
}

// class method to be task
public class TaskWork
{
  public void Work() {
    while(true){
      // task-repeated processing
    }
  }
}

c# .net multi-threaded

2022-09-30 21:21

2 Answers

Task is a concept that represents a set of actions to get results.For example, Stream.ReadAsync() returns a task to get read results.And there is no specification on how to run the task, and it is done in a way that you think is efficient.NET runtime.
In doing so, the default assumption is that the task will be completed in a short time, and many tasks will not be inadvertently run in parallel.If this is a task that runs for a long time, you should notify the nature of the task at runtime by specifying TaskCreationOptions.LongRunning.

Now that the code has been presented,

// Where to generate 10 threads
TaskWork = new TaskWork();
for(inti=0;i<10;i++){
    // Task.Run()=>taskWork.Work());
    Task.Factory.StartNew()=>taskWork.Work(), TaskCreationOptions.LongRunning);
}

What about

However, if you do not understand the concept of Task in the first place and have been chosen as an alternative to Thread or ThreadPool, it is recommended that you use the appropriate class instead of Task.


2022-09-30 21:21

There is a problem with what the task is doing.

Simply put, when you start four tasks, which is equal to the number of CPU cores, you use 100% of the CPU, and there is so little room for other tasks that you start very slowly.(Not at all)

Therefore, Thread.Sleep must be specified in TaskWork to pass execution opportunities to other threads.

while(true)
{
    // task-repeated processing
    Thread.Sleep (1000); // Sleep for 1 second
}

Sleep time is specified in milliseconds.0 if you don't want to give up CPU time as much as possible, and sleep only when necessary.


2022-09-30 21:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.