Executing a time method in another thread and timeout interruption

Hi, I am trying to run the async method to increase the time and cancel the method if the timeout is exceeded.

Ive tried to implement this using async and wait. But no luck. Perhaps im reorganizing this, any inputs would be appreciated

It should be noted that I can not change the interface "Their Interface" (hence the name)

Code so far:

using System;
using System.Diagnostics;

public interface TheirInterface
{
    void DoHeavyWork();
}

public class Result
{
    public TimeSpan Elapsed { get; set; }
    public Exception Exception { get; set; }

    public Result(TimeSpan elapsed, Exception exception)
    {
        Elapsed = elapsed;
        Exception = exception;
    }
}

public class TaskTest
{
    public void Start(TheirInterface impl)
    {
        int timeout = 10000;

        // TODO
        // Run HeavyWorkTimer(impl)
        // 
        // Wait for timeout, will be > 0
        // 
        // if timeout occurs abortheavy
    }

    public Result HeavyWorkTimer(TheirInterface impl)
    {
        var watch = new Stopwatch();

        try
        {
            watch.Start();
            impl.DoHeavyWork();
            watch.Stop();
        }
        catch (Exception ex)
        {
            watch.Stop();

            return new Result(watch.Elapsed, ex);
        }

        return new Result(watch.Elapsed, null);
    }
}
+2
source share
1 answer

, , , . Thread.Abort, . , , .

public Result HeavyWorkTimer(TheirInterface impl)
{
    var watch = new Stopwatch();
    Exception savedException = null;

    var workerThread = new Thread(() => 
    {
        try
        {
            watch.Start();
            impl.DoHeavyWork();
            watch.Stop();
        }
        catch (Exception ex)
        {
            watch.Stop();
            savedException = ex;
        }
    });

    // Create a timer to kill the worker thread after 5 seconds.
    var timeoutTimer = new System.Threading.Timer((s) =>
        {
            workerThread.Abort();
        }, null, TimeSpan.FromSeconds(5), TimeSpan.Infinite);

    workerThread.Start();

    workerThread.Join();

    return new Result(watch.Elapsed, savedException);
}

, , ThreadAbortException.

, , , Thread.Abort.

0

Source: https://habr.com/ru/post/1532140/


All Articles