Home > Backend Development > C++ > How to Cancel a Task.Wait() After a Timeout in C#?

How to Cancel a Task.Wait() After a Timeout in C#?

Mary-Kate Olsen
Release: 2025-01-27 22:16:13
Original
622 people have browsed it

How to Cancel a Task.Wait() After a Timeout in C#?

Timeout cancellation of Task.Wait() method in C#

In this code, MessageLoopWorker.Run is started on a new thread with a message pump, and the DoWorkAsync task is executed on this thread. Then wait for the task on the main thread, blocking the main thread until the task is completed.

In order to cancel the task after timeout, you can use the CancellationToken class. CancellationToken class allows you to propagate cancellation requests from one thread to another.

Here's how to modify your code to cancel the task after timeout:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

private Uri GetFinalUrl(PortalMerchant portalMerchant)

{

    SetBrowserFeatureControl();

    Uri finalUri = null;

    if (string.IsNullOrEmpty(portalMerchant.Url))

    {

        return null;

    }

    Uri trackingUrl = new Uri(portalMerchant.Url);

 

    // 创建一个 CancellationTokenSource。

    using (CancellationTokenSource cancellationTokenSource = new CancellationTokenSource())

    {

        // 设置 5 秒的超时时间。

        using (Timer timer = new Timer(state => cancellationTokenSource.Cancel(), null, 5000, Timeout.Infinite))

        {

            try

            {

                // 使用 CancellationToken 启动任务。

                var task = MessageLoopWorker.Run(DoWorkAsync, cancellationTokenSource.Token, trackingUrl);

 

                // 等待任务完成。

                task.Wait(cancellationTokenSource.Token);

 

                // 如果任务成功完成,获取结果。

                if (!string.IsNullOrEmpty(task.Result?.ToString()))

                {

                    return new Uri(task.Result.ToString());

                }

            }

            catch (OperationCanceledException)

            {

                // 任务被取消。

            }

            catch (AggregateException ex)

            {

                // 处理任务中的其他异常

                foreach (var innerException in ex.InnerExceptions)

                {

                    // Log or handle inner exception appropriately

                    Console.WriteLine($"Inner Exception: {innerException.Message}");

                }

            }

        }

    }

 

    // 如果任务被取消或失败,则返回 null。

    return null;

}

Copy after login

In this code, we create a CancellationTokenSource and pass it CancellationToken to the MessageLoopWorker.Run method. We also set a timer to cancel the token after 5 seconds. If the task completes successfully before timing out, we will get the result. If the task is cancelled, we capture OperationCanceledException. Finally, we release the using and CancellationTokenSource resources using the Timer statement to ensure the resources are handled correctly. Additionally, a AggregateException handler has been added to catch and handle other exceptions that may arise in the DoWorkAsync task.

This improved version uses using statements for proper resource management, preventing resource leaks. The addition of AggregateException handling makes the code more robust. Remember to handle the inner exceptions appropriately within the AggregateException catch block, such as logging them or taking other corrective actions.

The above is the detailed content of How to Cancel a Task.Wait() After a Timeout in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template