chmichael 12 Posted October 10, 2020 Hello, How can i Terminate/Kill a Parallel.Async ? example: Parallel.Async( procedure begin // Call a Winapi Blocking API which take 5000 ms to complete end ); Sleep(1000); //WaitFor 1000ms if MyParallelAsync still running kill it! Thank you Share this post Link to post
Vincent Parrett 763 Posted October 11, 2020 CancellationTokens are what you need. Parallel.Async as a second optional parameter which is an IOmniTaskConfig - you can create that using the Parallel.TaskConfig class function - then you need to create IOmniCancellationToken and pass that into the taskConfig.CancelWith - when you want to cancel the async, call cancellationtoken,Signal. Your procedure can also take an IOmniTask parameter which will give you access to the Cancellation token in your function, so you can gracefully exit eg Parallel.Async( procedure (const task : IOmniTask) begin // Call a Winapi Blocking API which take 5000 ms to complete if task.CancellationToken.IsSignalled then exit. end ); If the blocking api you call takes a handle or array of handles then you can use task.CancellationToken.Handle - eg in calls to WaitForSingleObject or WaitForMultipleObjects HTH Share this post Link to post
chmichael 12 Posted October 12, 2020 (edited) On 10/11/2020 at 5:07 AM, Vincent Parrett said: There is no point calling Async with CancellationToken since the above will timeout after 5000ms also! The reason i want to call it Async is because the API has 5000ms timeout and i want to timeout after 2000ms so in case it's still hasn't timeout i'll kill the async thread! Thank you Edited October 12, 2020 by chmichael Share this post Link to post
Vincent Parrett 763 Posted October 12, 2020 Umm, you might want to edit your reply so it doesn't look like I said it! What is the api you are calling? If an api you are calling is blocking, and doesn't take an event handle or have some way of cancelling then you cannot safely kill it. Killing a thread on windows is dangerous, https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-terminatethread Share this post Link to post
chmichael 12 Posted October 19, 2020 (edited) On 10/13/2020 at 12:00 AM, Vincent Parrett said: Umm, you might want to edit your reply so it doesn't look like I said it! What is the api you are calling? If an api you are calling is blocking, and doesn't take an event handle or have some way of cancelling then you cannot safely kill it. Killing a thread on windows is dangerous, https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-terminatethread Hello, Yes i know but i couldn't find any timeout for this API. It's the Winsock.Connect. Do you know how i can use the TerminateThread on Parallel.Async ? Thank you Edited October 19, 2020 by chmichael Share this post Link to post