.Net4.0如何实现.NET4.5中的Task.Run及Task.Delay方法

.Net4.0如何实现.NET4.5中的Task.Run及Task.Delay方法_.net framework 4 task.delay-CSDN博客

前言

在使用.net 4.0语法有点老旧,在习惯了使用Task.Run ,Task.Delay的情况下有点不适应,在网上找到一些方法后做了一些总结,主要是在Delay中增加了cancellationToken功能,当在延迟时,调用线程如果中断,则会退出Delay

public static Task Run(Action action)
{
    TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
    new Thread(() =>
    {
        try
        {
            action.Invoke();
            tcs.SetResult(null);
        }
        catch (Exception ex)
        {
            tcs.SetException(ex);                    
        }
    })
    { IsBackground = true}.Start();
    return tcs.Task;
}

public static Task<TReuslt> Run<TReuslt>(Func<TReuslt> function)
{
    TaskCompletionSource<TReuslt> tcs = new TaskCompletionSource<TReuslt>()
    new Thread(() =>
    {
        try
        {                    
            tcs.SetResult(function.Invoke());
        }
        catch (Exception ex)
        {
            tcs.SetException(ex);
        }
    })
    { IsBackground = true }.Start();
    return tcs.Task;
}
/// <summary>
/// 基本延迟功能
/// </summary>
/// <param name="milliseconds"></param>
/// <returns></returns>
public static Task Delay(int milliseconds)
        {
            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
            var timer = new System.Timers.Timer(milliseconds) { AutoReset = false};
            timer.Elapsed += delegate { 
                timer.Dispose();
                tcs.SetResult(null);
            };
            timer.Start();
            return tcs.Task;
        }
/// <summary>
/// 具有延迟和停止功能
/// </summary>
/// <param name="milliseconds"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static Task Delay(int milliseconds, CancellationToken cancellationToken)
{
    TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
    bool res = false;
    var timer = new System.Timers.Timer(milliseconds) { AutoReset = false };
    timer.Elapsed += delegate {
        timer.Dispose();
        res = true;
        tcs.SetResult(null);
    };
    timer.Start();
    while (!res)
    {
        if(cancellationToken.IsCancellationRequested)
        {
            timer.Stop();
            tcs.SetResult(null);                  
            break;
        }
    }
    return tcs.Task;
}

本来想写到Task中的扩展方法

public static Task Run(this Task task,Action action)
{
    TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
    new Thread(() =>
    {
        try
        {
            action.Invoke();
            tcs.SetResult(null);
        }
        catch (Exception ex)
        {
            tcs.SetException(ex);
        }
    })
    { IsBackground = true }.Start();
    return tcs.Task;
}

但是使用时还是不方便,如果有更好的方法可以留言交流一下