Пример #1
0
        private async Task <bool> WorkAsync(Func <ProfileItem, Task <bool> > perform, Func <ProfileItem, bool> judge, ProfileItem targetProfile = null)
        {
            var targetProfileCopy = targetProfile ?? Profiles.FirstOrDefault(x => x.IsTarget);

            if (targetProfileCopy == null)
            {
                return(false);
            }

            IsWorking.TurnOn();
            try
            {
                var timeoutTime = DateTime.Now.Add(_workingTimeoutDuration);

                if (!await perform(targetProfileCopy))
                {
                    return(false);
                }

                await Task.Delay(_workingFirstInterval);

                using (var cts = new CancellationTokenSource())
                {
                    while (timeoutTime > DateTime.Now)
                    {
                        try
                        {
                            await Task.WhenAll(
                                Task.Run(async() =>
                            {
                                await LoadProfilesAsync(false);

                                if (judge(targetProfileCopy))
                                {
                                    cts.Cancel();
                                }
                            }),
                                Task.Delay(_workingSecondInterval, cts.Token));
                        }
                        catch (TaskCanceledException)
                        {
                        }

                        if (cts.IsCancellationRequested)
                        {
                            return(true);
                        }
                    }
                    return(false);
                }
            }
            finally
            {
                IsWorking.TurnOff();
            }
        }
Пример #2
0
        private async Task <bool> WorkAsync(ProfileItem targetProfile, Func <ProfileItem, Task <bool> > perform)
        {
            try
            {
                Interlocked.Increment(ref _workCount);
                IsWorking.TurnOn();

                return(await perform.Invoke(targetProfile));
            }
            finally
            {
                if (Interlocked.Decrement(ref _workCount) == 0)
                {
                    IsWorking.TurnOff();
                }
            }
        }