Untitled

 avatar
unknown
plain_text
2 years ago
1.2 kB
4
Indexable
// Current Method
protected object WaitForData(string key, WaitForDataProfile profile)
{
    if (string.IsNullOrWhiteSpace(key))
        return null;

    if (profile == null)
    {
        profile = WaitForDataProfile.NORMAL;
    }

    object data = null;

    int count = 0;
    while (data == null && count < profile.Count)
    {
        Thread.Sleep(profile.MillisecondsDelay);
        data = GetCache(key, (TimeSpan?)null);
        count++;
    }

    return data;
}

// New Method

protected async Task<object> WaitForDataAsync(string key, WaitForDataProfile profile)
{
    if (string.IsNullOrWhiteSpace(key))
        return null;

    if (profile == null)
    {
        profile = WaitForDataProfile.NORMAL;
    }

    object data = null;

    using (var tcs = new TaskCompletionSource<object>())
    {
        int count = 0;
        while (data == null && count < 80)
        {
            await Task.Delay(profile.MillisecondsDelay);
            data = GetCache(key, (TimeSpan?)null);
            count++;
            if (data != null)
                tcs.SetResult(data);
        }
        return await tcs.Task;
    }
}
Editor is loading...