How do I cancel a schedule for a task? - c#

I need to create a scheduled task. For that I'm trying to learn how to do that, and am currently thinking of using TaskSchedulerClass from TaskScheduler Class Library. I got a code examples here (and there's another one I might try here). But - I don't want to actually run it without making sure I know how to cancel it when needed.
So my question is: How do I cancel such a task-registration in code?
(Just "Try it!" won't suffice in this case. Because the point is I don't want to get stuck with something I can't stop.)

What about TryDequeue Method?
It's attempts to dequeue a Task that was previously queued to this scheduler.
You need to use the same Task you sent to QueueTask function.
If you don't have the instance of this Task you can try and retrieve it using GetScheduledTasks, but it stated it in use For debugger support only

Related

How do I force a wait in the C# async await model

I think I must be missing something with my understanding of the async await model. What should be a simple thing seems to be unbelievably hard to achieve.
I have a UI which needs to check if the user is logged in. To do this I need to call a method in one of my classes which does some queries.
This class in turn calls 3rd party code which only has async methods.
How can I call that async method and make the application wait until I get a result?
I have tried all the things suggested such as ConfigureAwait, RunSynchronous, .Result, etc.. Nothing seems to reliably work.
It seems so stupid that something like this is so difficult so I assume I am missing a key piece of information.
Thanks.
Lets make something clear:
"make the application wait until I get a result?"
Has nothing to do (I cannot stress this enough) with blocking, awaiting or any result whatsoever.
If you are used of making the UI lock until something is done, you should switch your design, instead of trying to find a way to accomplish it.
(I have spent fair amount of time writing MFC apps for Windows Mobile, I used to do this as well)
The correct way to handle such situation, is to let the user know, that there is work being done (Some sort of Activity Indicator for example), and at the same time, make sure that no other code can be executed due to User Input (CanExecute property of your Command for example). When it is appropriate, you can put Cancelation logic.
Even more, in the context of MAUI (and mobile development in general), blocking the UI thread, even for few seconds, is totally not acceptable. It should remain responsive at all times. This is not a matter of choice.
You can use the Task.Result in the property to block the calling thread until the Task is completed. However, this is not recommended in most cases because it can lead to deadlocks. A better approach is to use await in a method marked as async, which will cause the method to return control to the calling method until the awaited Task is completed. If you need to block the thread, consider using ConfigureAwait(false) when awaiting the Task.
Read this for further information about the synchronous error handling to Async / Callback programs.

Cancel python function from dotnet (Python.NET)

I am using Python.NET to call the EasyOCR Python library. Depending on the context, the detection can be slow (from 30s to a couple of minutes) and some actions performed by my user could result in the cancellation of the task. As far as I can tell, the cancellation token will cancel the task only at the next C# instruction so I am stuck while the python code is running.
I have seen that there is some similar mechanism on Python side using asyncio but I was wondering if there was any way to avoid the complexity of having extra python logic by being able to somehow "kill" the python process. Or maybe some easy way to somehow share the token.
A feature very similar to what you are asking has been added to Python.NET recently (you might need to use 3.0 previews though, it probably did not make it into 2.5).
This is the test code, that was added for the feature. I think that is the best reference you will be able to get: https://github.com/pythonnet/pythonnet/pull/1337/files#diff-e846713ba20ecf06af2cc88cc1e92bae49d519998b093d2fb0f7fd6644b10092
Pay attention to the SetUp method too. It shows how to correctly set up multithreading.
There is no good way to abort a non-cooperating thread/task. There is Thread.Abort, but using it is a bad idea. Your options are more or less
Figure out a way to forward the cancellation request to the python code.
Stop waiting for the result when cancelling the task, but let the task continue to run in the background.
Run the task in a separate process, and kill the process on cancel.
Do not allow the task to be cancelled.

Is it good practice to always wait on a task to complete?

Sorry if it is a dumb question. I'm confused about the wait() and its variants in regards to the task parallel library.
Every single example I've seen waits on tasks to complete - is this considered good practice?
My scenario is this, that I'm developing a windows service that will run continuously. I would like to engage a number of tasks, but I don't care if they will run to completion - I will set a cancellation-token with an expiration, that will throw an error if something goes awry. So I don't see the need for a wait-to-complete, but every darn example uses it...
It really depends on what your situations needs. If for instance, you want to launch a sub process to do a procedure, say for instance, fire off an email in parallel you can do without waiting.
However, if you will need to act upon what ever result or structure which is affected by some behavior you will need to wait.
If your tasks are self contained and do not interact and/or depend on each other, then I do not see why you would need to wait.
You only need to wait on a task if the code that is waiting requires the output of the task before it can proceed. If you don't need that output, don't wait.

async await best practices

I've grasped the concept of async await and have been using it sporadically, but do have a couple questions regarding best practices.
is it ok to use await in a while(condition) loop to keep fetching data that may be present, until the while condition changes, e.g. stopProcessingMessages = false.
in an application such as winforms, while UI runs on it's thread, using async/await on an operation such as a button click is fairly trivial, but what about if I would like to enforce asynchronously throughout an entire console application, or even a windows service. what is the best practice to initially kick off that first await task, would that be Task.Run (() => ... )?
I hope I am making sense in my 2nd question. I want to make the most of async and utilize it to it's full extent, but just need to understand how to kick off the initial asynchronous operation before it bubbles down to all other asynchronous functions.
apologies for not using the proper code blocks I am on the train using my smartphone.
I've grasped the concept of async await and have been using it sporadically, but do have a couple questions regarding best practices.
I have an intro to async/await blog post that goes into more detail than most intros and also introduces several best practices.
is it ok to use await in a while(condition) loop to keep fetching data that may be present, until the while condition changes, e.g. stopProcessingMessages = false.
You want to avoid tight loops. So the while (condition) GetDataIfPresent(); is going to consume a lot of CPU.
Alternatively, you could use an async method that returned null (or whatever) if stopProcessingMessages is true. In this case, your code would be while (true), and a more TAP-like solution would be to use CancellationSource instead of a flag.
Also take a look at TPL Dataflow; it sounds like it may be useful for your kind of situation.
console application, or even a windows service. what is the best practice to initially kick off that first await task
For console apps, you could Wait on the top-level task. This is an acceptable exception to the usual guideline (which is to await instead of Wait). Waiting will burn a thread for the duration of the console app, but that's usually not important enough to warrant a more complex solution. If you do want to install a single-threaded context for your console app, you could use AsyncContext.Run from my AsyncEx library.
For Win32 services, you usually do need to start your own thread. You can use Task.Run for this (if you want a multithreaded context), or AsyncContextThread from AsyncEx (if you want a single-threaded context).
Good morning,
I would rather use a regular task with the TaskCreationOption set to 'LongRunning' in your first scenario than the async/await pattern.
This way your whole while block would be executed in one long running task. When using await inside each while loop you would start a new task with every loop - would work, but it's maybe not so optimal ;-)
Regarding your second question, I'm sorry but I don't get your point.
Hope this helps.
It is not ok to use a loop to keep fething data that may be present..
You can create an async call that upon completion will automaticlly invoke a callback method.. the "waiting" phase in that case will happen in the OS mechanisms which treat this waiting phase in optimum way to the OS being used.
Take a look here for further study of the subject:
http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx

How do I make a .NET 4 thread wait for asynchronous requests to finish?

I am using HttpWebRequest.BeginGetRequest() to make 500 asynchronous HTTP requests from a single method. I would like that method to wait until I get a response from all the requests or they timeout.
What is the best way to do this?
I'm currently wrapping the asynchronous calls within a List of Task objects to use Tasks.WaitAll(), but I don't want to go too far down the rabbit hole before I know that this is a good solution.
Any ideas?
EDIT
I implemented counters, and they work, but I'm curious about using delegates like shown on this page.
Multi-threading and Async Examples
Has anybody done something like this before? Is it overkill?
I'm currently wrapping the asynchronous calls within a List of Task objects to use Tasks.WaitAll()
This is a fairly clean solution if you truly want to force these "tasks" to synchronize and block at this point. This is the main rationale behind Task.WaitAll(), and is nice since it (optionally) allows you to cancel the blocking operation after a timeout, if you so choose.
Personally I wouldn't block the thread, it defeats the purpose of the async model.
If I absolutely had to wait for these web requests to finish before continuing I would instead keep a counter that is incremented each time you get called back on a successful or failed request.
Check the counter on each callback and if it has hit your desired count then let the thread continue...
This way you can also keep your UI nice and responsive and perhaps update a counter/progress bar - Even if you're not kicking these off on the UI thread it's nice to provide some visual feed back tot he user about what is going on.

Categories