Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Task does not work when with return value with Timeout

I want to create a task to return value that with 5 seconds timeout (desktop application).

Here is my sample code:

public async Task<int> Initialize()
{
    try
    {
        var _result = await (new Task<int>(() =>
        {
            int i = 1;
            ///some code
            return i;
        })).WaitAsync(TimeSpan.FromSeconds(5));
        return _result;
    }
    catch (TimeoutException)
    {
        return -1;
    }
    catch {
        return -2;
    }
}

The framework I am using is .Net8.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Why does the task never start even if I add a break point that always return a TimeoutException.

>Solution :

As you can see right here, task actually executing properly

The only think u need to do, hm so, i guess it is just running this task. Because this is a task btw .-.

After that u should be fine <- This picture

About more information because i use Task.Run() only as example, use in parallel couse a lot of cases needs it: Executing tasks in parallel

Hope it helps

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading