Skip to content

Latest commit

 

History

History
47 lines (47 loc) · 1.38 KB

20181130.Task封装-SQLTask.md

File metadata and controls

47 lines (47 loc) · 1.38 KB
public static class SQLTask
{
    public static Task<T> SQLTaskExecute<T>(Func<Task<T>> func, int millisecondsDelay = 5000)
    {
        var ts = new TaskCompletionSource<T>();
        var token = new CancellationTokenSource(millisecondsDelay);
        Task.Run(func, token.Token).ContinueWith((t) =>
        {
            if (t.Exception == null && !t.IsCanceled)
            {
                ts.TrySetResult(t.Result);
            }
            else if (t.Exception != null)
            {
                ts.TrySetException(t.Exception);
            }
            else if (t.IsCanceled)
            {
                ts.TrySetCanceled();
            }
        }).ConfigureAwait(false);
        return ts.Task;
    }
    public static Task SQLTaskExecute(Func<Task> func, int millisecondsDelay = 5000)
    {
        var ts = new TaskCompletionSource<bool>();
        var token = new CancellationTokenSource(millisecondsDelay);
        Task.Run(func, token.Token).ContinueWith((t) =>
        {
            if (t.Exception == null && !t.IsCanceled)
            {
                ts.TrySetResult(true);
            }
            else if (t.Exception != null)
            {
                ts.TrySetException(t.Exception);
            }
            else if (t.IsCanceled)
            {
                ts.TrySetCanceled();
            }
        }).ConfigureAwait(false);
        return ts.Task;
    }
}