Wapac
Wapac

Reputation: 4178

Long running async task and long running time limited async task in C#

I have two situations that I'm not sure how to resolve properly. First is a task that runs for as long as the application. Currently, I have a construction like this:

this.task = this.joinableTaskFactory.RunAsync(async () => await this.TaskProcedureAsync().ConfigureAwait(false), JoinableTaskCreationOptions.LongRunning);

Here TaskProcedureAsync is usually a loop until the application end signal is received and inside of it is await of some sort that provides a job to complete (e.g. from an async queue), when it arrives, it is processed and then it waits again for the next job.

Here I'm not sure if running with JoinableTaskCreationOptions.LongRunning is a correct solution for such a task. In DisposeCoreAsync then I await this joinable task:

            await this.task.JoinAsync().ConfigureAwait(false);

and then do the rest of the disposal work. So the question here, if this is right thing to do in such scenario or if there is a better way to run such long running async task. This seems to work fine as it is, just not sure if it is optimal regarding the internal management of threads. There are not that many of these loops in the application, up to 30 is a reasonable expectation for my application.

The follow up problem I am quite sure that does not work well as I have it now. Besides those loop tasks that I have that run for as long as the application, I also have a bigger number of long running task that are supposed to be strictly time limited. Currently I use TplExtensions.WithTimeout extension:

result = await script.InitializeAsync().WithTimeout(TimeSpan.FromSeconds(ScriptInitializationTimeoutSeconds)).ConfigureAwait(false);

Basically I am running an untrusted code that must be stopped after certain limit. Now the problem is that WithTimeout does not stop the task itself, only throws exception after the time is out. The question here is how to implement this properly? I was thinking that if the code is to be stopped, it should be run in its own thread as a thread can be killed while task can not. But then I've read here that such an approach would not work because I could only execute synchronous code in such a thread and not async code.

Is there any way to kill the task then? Can I for example kill the thread that currently executes the task? Or how is this done properly?

Upvotes: 0

Views: 571

Answers (0)

Related Questions