There is a method of a third-party library. It accesses the server and either receives the data and terminates, or automatically closes after 10 seconds. Completion of the method in less than 10 seconds is not provided. I need to close it after 100 milliseconds of work. I would like to do this without multithreading. Any idea how to do this?

  • Asynchronous execution. To cancel the task, use the cancel token - Vadim Prokopchuk
  • Can you bring an example of execution - polsok

2 answers 2

Bring

It is much more convenient to compose the composition of asynchronous operations using Task s. Therefore, see if your third-party library api has Task s support?

If yes, then your answer in these lines

  static void Main(string[] args) { CancellationTokenSource cts = new CancellationTokenSource(); cts.CancelAfter(100);//отменяет задачу после указанного числа миллисекунд var res = TaskWrap(cts.Token);//функции с поддержками тасков обычно имеют перегрузку с CancellationToken Console.WriteLine(res.Result); } 

If api of a third-party library does not support Task and, then it is necessary to wrap the response callback in the TaskCompletionSource and continue working with the task

  static Task<string> TaskWrap(CancellationToken ct) { TaskCompletionSource<string> tcs = new TaskCompletionSource<string>(); ct.Register(()=> {/* остановить загрузку, чтоб данные больше приходили, если это возможно*/ tcs.SetException(new TimeoutException()); }); YourFunctionCallback(answer => tcs.SetResult(answer)); return tcs.Task; } 

    If you don’t have the source code for the method You can not stop someone else's code.

    Proper implementation of job cancellation is cooperative: the code you want to stop must cooperate . If you interrupt it in some way, then at best you will leave its data structures in a non-consistent state, and in the worst - interrupt the execution of the native code in the state of a locked heap lock.

    If the library does not cooperate, do not use it or request / ask the authors for the legal ability to control the cancellation.


    Of course, you can run a third-party method in the next thread, and at the end of the timeout just spit on this code and allow it to run further, ignoring the result. This, of course, is not the best design: you block the flow for a long time for the sake of one short operation.