System.Threading.Tasks.Task.Run(System.Func)

Here are the examples of the csharp api System.Threading.Tasks.Task.Run(System.Func) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

4201 Examples 7

19 Source : LavalinkNodeConnection.cs
with MIT License
from Aiko-IT-Systems

private Task Discord_VoiceStateUpdated(DiscordClient client, VoiceStateUpdateEventArgs e)
        {
            var gld = e.Guild;
            if (gld == null)
                return Task.CompletedTask;

            if (e.User == null)
                return Task.CompletedTask;

            if (e.User.Id == this.Discord.CurrentUser.Id)
            {
                if (this._connectedGuilds.TryGetValue(e.Guild.Id, out var lvlgc))
                    lvlgc.VoiceStateUpdate = e;

                if (e.After.Channel == null && this.IsConnected && this._connectedGuilds.ContainsKey(gld.Id))
                {
                    _ = Task.Run(async () =>
                    {
                        var delayTask = Task.Delay(this.Configuration.WebSocketCloseTimeout);
                        var tcs = lvlgc.VoiceWsDisconnectTcs.Task;
                        _ = await Task.WhenAny(delayTask, tcs).ConfigureAwait(false);

                        await lvlgc.DisconnectInternalAsync(false, true).ConfigureAwait(false);
                        _ = this._connectedGuilds.TryRemove(gld.Id, out _);
                    });
                }

                if (!string.IsNullOrWhiteSpace(e.SessionId) && e.Channel != null && this.VoiceStateUpdates.TryRemove(gld.Id, out var xe))
                    xe.SetResult(e);
            }

            return Task.CompletedTask;
        }

19 Source : SplunkETW.cs
with Apache License 2.0
from airbus-cert

public override async Task StreamEventsAsync(InputDefinition inputDefinition, EventWriter eventWriter)
        {
            var splunkHome = Environment.GetEnvironmentVariable("SPLUNK_HOME");
            var profile = inputDefinition.Name.Split(new string[] { "://" }, StringSplitOptions.RemoveEmptyEntries)[1];
            await eventWriter.LogAsync(Severity.Info, "Splunk-ETW select " + profile + " profile");

            string iniPath = Path.Combine(new string[] { splunkHome, "etc", "apps", "Splunk-ETW", "profile", profile + ".ini" });
            await eventWriter.LogAsync(Severity.Info, "Splunk-ETW load " + iniPath);

            try
            {
                var trace = TraceManager.BuildFromConfig(new FileIniDataParser().ReadFile(iniPath), new SplunkWriter(eventWriter, inputDefinition.Name));
                await Task.Run(() => trace.Start());
            }
            catch(Exception e)
            {
                await eventWriter.LogAsync(Severity.Error, e.ToString());
            }
        }

19 Source : RetryableWebSocketConnection.cs
with MIT License
from AiursoftWeb

private async Task PullAndMonitorInThisThread(Func<List<Commit<T>>, Task> onData, Func<string> startPositionFactory, Func<Task> onConnected)
        {
            var exitTask = Task.Run(() => _exitEvent.WaitOne());
            var retryGapSeconds = 1;
            var connectedTime = DateTime.MinValue;
            while (!exitTask.IsCompleted)
            {
                try
                {
                    connectedTime = DateTime.UtcNow;

                    AttemptCount++;

                    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(AttemptCount)));

                    await base.PullAndMonitor(onData, startPositionFactory, onConnected: () => 
                    {
                        IsConnectionHealthy = true;
                        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsConnectionHealthy)));
                        return onConnected();
                    }, true);
                }
                catch (WebSocketException)
                {
                    IsConnectionHealthy = false;
                    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsConnectionHealthy)));
                    OnReconnecting?.Invoke();
                    if (DateTime.UtcNow - connectedTime > TimeSpan.FromMinutes(1))
                    {
                        // Connection held for one minute. Seems to be a healthy server. Retry soon.
                        retryGapSeconds = 1;
                    }

                    // When retry time finish, or asked to finished.
                    await Task.WhenAny(Task.Delay(TimeSpan.FromSeconds(retryGapSeconds)), exitTask);
                    if (retryGapSeconds < 128)
                    {
                        retryGapSeconds *= 2;
                    }
                }
            }
        }

19 Source : BotCommander.cs
with MIT License
from AiursoftWeb

public Task Command()
        {
            return Task.Run(CommandLoop);
        }

19 Source : ParserBase.cs
with MIT License
from aivarasatk

protected async Task<string> BaseParseMagnet(string pageContents)
        {
            return await Task.Run(() =>
            {
                var htmlAgility = LoadedHtmlDoreplacedent(pageContents);

                var magnetNode = htmlAgility.DoreplacedentNode
                                            .SelectNodes("//a")
                                            .FirstOrDefault(a => a.Attributes.Any(atr => atr.Name == "href" && atr.Value.Contains("magnet")));

                if (magnetNode == null)
                    throw new Exception($"Magnet node is not found");

                return magnetNode.Attributes.First(m => m.Name == "href").Value;
            });
        }

19 Source : MergeTest.cs
with Apache License 2.0
from akarnokd

[Fact]
        public async void Push()
        {
            for (var i = 0; i < 10; i++)
            {
                var push = new MulticastAsyncEnumerable<int>();

                var en = AsyncEnumerable.Merge(
                        push.Filter(v => v % 2 == 0), 
                        push.Filter(v => v % 2 != 0)
                    )
                    .ToListAsync();

                var t = Task.Run(async () =>
                {
                    for (var j = 0; j < 100_000; j++)
                    {
                        await push.Next(j);
                    }
                    await push.Complete();
                });

                var list = await en;

                await t;

                var set = new HashSet<int>(list);

                replacedert.Equal(100_000, set.Count);
            }
        }

19 Source : MulticastAsyncEnumerableTest.cs
with Apache License 2.0
from akarnokd

[Fact]
        public async void Normal_One_Consumer()
        {
            var push = new MulticastAsyncEnumerable<int>();

            var en1 = push.GetAsyncEnumerator(default);

            var task = Task.Run(async () =>
            {
                await en1.replacedertResult(1, 2, 3, 4, 5);
            });

            for (var i = 1; i <= 5; i++)
            {
                await push.Next(i);
            }
            await push.Complete();

            await task;
        }

19 Source : MulticastAsyncEnumerableTest.cs
with Apache License 2.0
from akarnokd

[Fact]
        public async void Error_One_Consumer()
        {
            var push = new MulticastAsyncEnumerable<int>();

            var en1 = push.GetAsyncEnumerator(default);

            var task = Task.Run(async () =>
            {
                await en1.replacedertFailure(typeof(InvalidOperationException), 1, 2, 3, 4, 5);
            });

            for (var i = 1; i <= 5; i++)
            {
                await push.Next(i);
            }
            await push.Error(new InvalidOperationException());

            await task;
        }

19 Source : MulticastAsyncEnumerableTest.cs
with Apache License 2.0
from akarnokd

[Fact]
        public async void Normal_2_Consumers()
        {
            var push = new MulticastAsyncEnumerable<int>();

            var en1 = push.GetAsyncEnumerator(default);

            var task1 = Task.Run(async () =>
            {
                await en1.replacedertResult(1, 2, 3, 4, 5);
            });

            var en2 = push.GetAsyncEnumerator(default);
            var task2 = Task.Run(async () =>
            {
                await en2.replacedertResult(1, 2, 3, 4, 5);
            });

            for (var i = 1; i <= 5; i++)
            {
                await push.Next(i);
            }
            await push.Complete();

            await task1;
            await task2;
        }

19 Source : MulticastAsyncEnumerableTest.cs
with Apache License 2.0
from akarnokd

[Fact]
        public async void Error_2_Consumers()
        {
            var push = new MulticastAsyncEnumerable<int>();

            var en1 = push.GetAsyncEnumerator(default);


            var en2 = push.GetAsyncEnumerator(default);

            var task1 = Task.Run(async () =>
            {
                await en1.replacedertFailure(typeof(InvalidOperationException), 1, 2, 3, 4, 5);
            });
            var task2 = Task.Run(async () =>
            {
                await en2.replacedertFailure(typeof(InvalidOperationException), 1, 2, 3, 4, 5);
            });

            for (var i = 1; i <= 5; i++)
            {
                await push.Next(i);
            }
            await push.Error(new InvalidOperationException());

            await task1;
            await task2;
        }

19 Source : MulticastAsyncEnumerableTest.cs
with Apache License 2.0
from akarnokd

[Fact]
        public async void Normal_2_Consumers_One_Take()
        {
            var push = new MulticastAsyncEnumerable<int>();

            var en1 = push.Take(3).GetAsyncEnumerator(default);

            var task1 = Task.Run(async () =>
            {
                await en1.replacedertResult(1, 2, 3);
            });

            var en2 = push.GetAsyncEnumerator(default);
            var task2 = Task.Run(async () =>
            {
                await en2.replacedertResult(1, 2, 3, 4, 5);
            });

            for (var i = 1; i <= 5; i++)
            {
                await push.Next(i);
            }
            await push.Complete();

            await task1;
            await task2;
        }

19 Source : ReplayAsyncEnumerableTest.cs
with Apache License 2.0
from akarnokd

[Fact]
        public async void Unbounded_One_Consumer()
        {
            var push = new ReplayAsyncEnumerable<int>();

            var en1 = push.GetAsyncEnumerator(default);

            var task1 = Task.Run(async () =>
            {
                await en1.replacedertResult(1, 2, 3, 4, 5);
            });

            for (var i = 1; i <= 5; i++)
            {
                await push.Next(i);
            }
            await push.Complete();

            await task1;
        }

19 Source : ReplayAsyncEnumerableTest.cs
with Apache License 2.0
from akarnokd

[Fact]
        public async void Unbounded_One_Consumer_Error()
        {
            var push = new ReplayAsyncEnumerable<int>();

            var en1 = push.GetAsyncEnumerator(default);

            var task1 = Task.Run(async () =>
            {
                await en1.replacedertFailure(typeof(InvalidOperationException), 1, 2, 3, 4, 5);
            });

            for (var i = 1; i <= 5; i++)
            {
                await push.Next(i);
            }
            await push.Error(new InvalidOperationException());

            await task1;
        }

19 Source : ReplayAsyncEnumerableTest.cs
with Apache License 2.0
from akarnokd

[Fact]
        public async void Unbounded_2_Consumers()
        {
            var push = new ReplayAsyncEnumerable<int>();

            var en1 = push.GetAsyncEnumerator(default);
            var en2 = push.GetAsyncEnumerator(default);

            var task1 = Task.Run(async () =>
            {
                await en1.replacedertResult(1, 2, 3, 4, 5);
            });
            var task2 = Task.Run(async () =>
            {
                await en2.replacedertResult(1, 2, 3, 4, 5);
            });

            for (var i = 1; i <= 5; i++)
            {
                await push.Next(i);
            }
            await push.Complete();

            await task1;
            await task2;
        }

19 Source : ReplayAsyncEnumerableTest.cs
with Apache License 2.0
from akarnokd

[Fact]
        public async void Unbounded_2_Consumers_Error()
        {
            var push = new ReplayAsyncEnumerable<int>();

            var en1 = push.GetAsyncEnumerator(default);
            var en2 = push.GetAsyncEnumerator(default);

            var task1 = Task.Run(async () =>
            {
                await en1.replacedertFailure(typeof(InvalidOperationException), 1, 2, 3, 4, 5);
            });
            var task2 = Task.Run(async () =>
            {
                await en2.replacedertFailure(typeof(InvalidOperationException), 1, 2, 3, 4, 5);
            });

            for (var i = 1; i <= 5; i++)
            {
                await push.Next(i);
            }
            await push.Error(new InvalidOperationException());

            await task1;
            await task2;
        }

19 Source : ReplayAsyncEnumerableTest.cs
with Apache License 2.0
from akarnokd

[Fact]
        public async void Sized_One_Consumer()
        {
            var push = new ReplayAsyncEnumerable<int>(10);

            var en1 = push.GetAsyncEnumerator(default);

            var task1 = Task.Run(async () =>
            {
                await en1.replacedertResult(1, 2, 3, 4, 5);
            });

            for (var i = 1; i <= 5; i++)
            {
                await push.Next(i);
            }
            await push.Complete();

            await task1;
        }

19 Source : ReplayAsyncEnumerableTest.cs
with Apache License 2.0
from akarnokd

[Fact]
        public async void Sized_One_Consumer_Error()
        {
            var push = new ReplayAsyncEnumerable<int>(10);

            var en1 = push.GetAsyncEnumerator(default);

            var task1 = Task.Run(async () =>
            {
                await en1.replacedertFailure(typeof(InvalidOperationException), 1, 2, 3, 4, 5);
            });

            for (var i = 1; i <= 5; i++)
            {
                await push.Next(i);
            }
            await push.Error(new InvalidOperationException());

            await task1;
        }

19 Source : ReplayAsyncEnumerableTest.cs
with Apache License 2.0
from akarnokd

[Fact]
        public async void Sized_2_Consumers()
        {
            var push = new ReplayAsyncEnumerable<int>(10);

            var en1 = push.GetAsyncEnumerator(default);
            var en2 = push.GetAsyncEnumerator(default);

            var task1 = Task.Run(async () =>
            {
                await en1.replacedertResult(1, 2, 3, 4, 5);
            });
            var task2 = Task.Run(async () =>
            {
                await en2.replacedertResult(1, 2, 3, 4, 5);
            });

            for (var i = 1; i <= 5; i++)
            {
                await push.Next(i);
            }
            await push.Complete();

            await task1;
            await task2;
        }

19 Source : ReplayAsyncEnumerableTest.cs
with Apache License 2.0
from akarnokd

[Fact]
        public async void Sized_2_Consumers_Error()
        {
            var push = new ReplayAsyncEnumerable<int>(10);

            var en1 = push.GetAsyncEnumerator(default);
            var en2 = push.GetAsyncEnumerator(default);

            var task1 = Task.Run(async () =>
            {
                await en1.replacedertFailure(typeof(InvalidOperationException), 1, 2, 3, 4, 5);
            });
            var task2 = Task.Run(async () =>
            {
                await en2.replacedertFailure(typeof(InvalidOperationException), 1, 2, 3, 4, 5);
            });

            for (var i = 1; i <= 5; i++)
            {
                await push.Next(i);
            }
            await push.Error(new InvalidOperationException());

            await task1;
            await task2;
        }

19 Source : ReplayAsyncEnumerableTest.cs
with Apache License 2.0
from akarnokd

[Fact]
        public async void TimedSized_One_Consumer()
        {
            var push = new ReplayAsyncEnumerable<int>(10, TimeSpan.FromHours(1));

            var en1 = push.GetAsyncEnumerator(default);

            var task1 = Task.Run(async () =>
            {
                await en1.replacedertResult(1, 2, 3, 4, 5);
            });

            for (var i = 1; i <= 5; i++)
            {
                await push.Next(i);
            }
            await push.Complete();

            await task1;
        }

19 Source : ReplayAsyncEnumerableTest.cs
with Apache License 2.0
from akarnokd

[Fact]
        public async void TimedSized_One_Consumer_Error()
        {
            var push = new ReplayAsyncEnumerable<int>(10, TimeSpan.FromHours(1));

            var en1 = push.GetAsyncEnumerator(default);

            var task1 = Task.Run(async () =>
            {
                await en1.replacedertFailure(typeof(InvalidOperationException), 1, 2, 3, 4, 5);
            });

            for (var i = 1; i <= 5; i++)
            {
                await push.Next(i);
            }
            await push.Error(new InvalidOperationException());

            await task1;
        }

19 Source : ReplayAsyncEnumerableTest.cs
with Apache License 2.0
from akarnokd

[Fact]
        public async void TimedSized_2_Consumers()
        {
            var push = new ReplayAsyncEnumerable<int>(10, TimeSpan.FromHours(1));

            var en1 = push.GetAsyncEnumerator(default);
            var en2 = push.GetAsyncEnumerator(default);

            var task1 = Task.Run(async () =>
            {
                await en1.replacedertResult(1, 2, 3, 4, 5);
            });
            var task2 = Task.Run(async () =>
            {
                await en2.replacedertResult(1, 2, 3, 4, 5);
            });

            for (var i = 1; i <= 5; i++)
            {
                await push.Next(i);
            }
            await push.Complete();

            await task1;
            await task2;
        }

19 Source : ReplayAsyncEnumerableTest.cs
with Apache License 2.0
from akarnokd

[Fact]
        public async void TimedSized_2_Consumers_Error()
        {
            var push = new ReplayAsyncEnumerable<int>(10, TimeSpan.FromHours(1));

            var en1 = push.GetAsyncEnumerator(default);
            var en2 = push.GetAsyncEnumerator(default);

            var task1 = Task.Run(async () =>
            {
                await en1.replacedertFailure(typeof(InvalidOperationException), 1, 2, 3, 4, 5);
            });
            var task2 = Task.Run(async () =>
            {
                await en2.replacedertFailure(typeof(InvalidOperationException), 1, 2, 3, 4, 5);
            });

            for (var i = 1; i <= 5; i++)
            {
                await push.Next(i);
            }
            await push.Error(new InvalidOperationException());

            await task1;
            await task2;
        }

19 Source : FlowableFromTask1Tck.cs
with Apache License 2.0
from akarnokd

public override IPublisher<int> CreatePublisher(long elements)
        {
            return Flowable.FromTask(Task.Run<int>(() => 1));
        }

19 Source : OutfitCompatibility.cs
with MIT License
from AkiniKites

public async Task<Dictionary<BaseGGUUID, BaseGGUUID>> UpdateVariants(
            string path, Dictionary<BaseGGUUID, BaseGGUUID> mapping)
        {
            if (!FileCompatibility.ShouldMigrate(path, new Version(1, 7, 5)))
                return mapping;

            if (_outfitCharGen == null)
            {
                _allCharGen = new AllCharacterGenerator();
                _outfitCharGen = new OutfitCharacterGenerator(_allCharGen);
            }

            var allModels = await Task.Run(() => _outfitCharGen.GetCharacterModels(true));

            var modelRemapping = new Dictionary<BaseGGUUID, BaseGGUUID>();
            foreach (var modelGroup in allModels.GroupBy(x => x.Name))
            {
                var newModel = modelGroup.OrderBy(_allCharGen.GetModelSorting).First();
                foreach (var model in modelGroup)
                    modelRemapping.Add(model.Id, newModel.Id);
            }

            var newMapping = new Dictionary<BaseGGUUID, BaseGGUUID>();
            foreach (var map in mapping)
            {
                if (!modelRemapping.TryGetValue(map.Value, out var id))
                    id = map.Value;
                
                newMapping.Add(map.Key, id);
            }

            return newMapping;
        }

19 Source : Coroutine.cs
with GNU Affero General Public License v3.0
from akira0245

public static async Task WaitWhile(Func<bool> condition, int timeout = -1, int frequency = 25)
    {
        var waitTask = Task.Run(async () =>
        {
            while (condition())
            {
                await Task.Delay(frequency);
            }
        });

        if (waitTask != await Task.WhenAny(waitTask, Task.Delay(timeout)))
        {
            throw new TimeoutException();
        }
    }

19 Source : Coroutine.cs
with GNU Affero General Public License v3.0
from akira0245

public static async Task WaitUntil(Func<bool> condition, int timeout = -1, int frequency = 25)
    {
        var waitTask = Task.Run(async () =>
        {
            while (!condition())
            {
                await Task.Delay(frequency);
            }
        });

        if (waitTask != await Task.WhenAny(
                waitTask,
                Task.Delay(timeout)))
        {
            throw new TimeoutException();
        }
    }

19 Source : ExternalFileKeysProvider.cs
with MIT License
from aksoftware98

private StorageFile GetFile(string fileName)
        {
            var task = Task.Run(async () => await LocalizationFolder.GetFileAsync(fileName));
            if (!task.IsFaulted)
            {
                return task.Result;
            }
            throw task.Exception;
        }

19 Source : ExternalFileKeysProvider.cs
with MIT License
from aksoftware98

protected override string[] GetLanguageFileNames()
        {
            var task = Task.Run(async () => await LocalizationFolder.GetFilesAsync());
            if (!task.IsFaulted)
            {
                var files = task.Result;
                return files.Select(file => file.Name).ToArray();
            }
            throw task.Exception;
           
        }

19 Source : KInMemoryStore.cs
with MIT License
from alethic

public async Task StartAsync(CancellationToken cancellationToken = default)
        {
            using (await sync.LockAsync(cancellationToken))
            {
                if (run != null || runCts != null)
                    throw new InvalidOperationException();

                // begin new run processes
                runCts = new CancellationTokenSource();
                run = Task.WhenAll(
                    Task.Run(() => ExpireRunAsync(runCts.Token)),
                    Task.Run(() => ReplicateRunAsync(runCts.Token)));
            }
        }

19 Source : KInMemoryPublisher.cs
with MIT License
from alethic

public async Task StartAsync(CancellationToken cancellationToken = default)
        {
            using (await sync.LockAsync(cancellationToken))
            {
                if (run != null || runCts != null)
                    throw new InvalidOperationException();

                // begin new run processes
                runCts = new CancellationTokenSource();
                run = Task.WhenAll(Task.Run(() => PublishRunAsync(runCts.Token)));
            }
        }

19 Source : AppHostCommunicationListener.cs
with MIT License
from alethic

public async Task<string> OpenAsync(CancellationToken cancellationToken)
        {
            var endpoint = serviceContext.CodePackageActivationContext.GetEndpoint(endpointName);
            if (endpoint == null)
                throw new InvalidOperationException($"Endpoint not found: {endpointName}.");

            // derive binding information from endpoint
            if (endpoint.UriScheme != "http")
                throw new InvalidOperationException("Only endpoints with UriSchema of 'http' are supported.");

            // generate app host
            appHost = build(new[] { new BindingData("http", $"*:{endpoint.Port}:*") }, "/", this);
            if (appHost == null)
                throw new AppHostException("Invalid AppHost.");

            // start application host
            await Task.Run(() => appHost.Start());

            // return final listen address
            return $"http://{serviceContext.NodeContext.IPAddressOrFQDN}:{endpoint.Port}";
        }

19 Source : AppHostCommunicationListener.cs
with MIT License
from alethic

public async Task CloseAsync(CancellationToken cancellationToken)
        {
            if (appHost != null)
            {
                await Task.Run(() => appHost.Stop());
                appHost = null;
            }
        }

19 Source : KRefresher.cs
with MIT License
from alethic

public async Task StartAsync(CancellationToken cancellationToken = default)
        {
            logger.LogInformation("Starting periodic refresher.");

            using (await sync.LockAsync(cancellationToken))
            {
                if (run != null || runCts != null)
                    throw new InvalidOperationException();

                // begin new run processes
                runCts = new CancellationTokenSource();
                run = Task.WhenAll(Task.Run(() => PeriodicRefreshAsync(runCts.Token)));
            }
        }

19 Source : KStaticDiscovery.cs
with MIT License
from alethic

public async Task StartAsync(CancellationToken cancellationToken)
        {
            using (await sync.LockAsync(cancellationToken))
            {
                if (run != null || runCts != null)
                    throw new InvalidOperationException();

                // begin new run processes
                runCts = new CancellationTokenSource();
                run = Task.WhenAll(Task.Run(() => DiscoveryRunAsync(runCts.Token)));

                // also connect when endpoints come and go
                host.EndpointsChanged += OnEndpointsChanged;
            }
        }

19 Source : KInMemoryStore.cs
with MIT License
from alethic

async Task ReplicateRunAsync(CancellationToken cancellationToken)
        {
            while (cancellationToken.IsCancellationRequested == false)
            {
                try
                {
                    List<Task> l = null;

                    using (slim.BeginUpgradableReadLock())
                    {
                        // continue while the first item is expired
                        while (
                            repQueue.Count > 0 &&
                            repQueue.FindMin() is Entry entry &&
                            entry.ReplicateTime != null &&
                            entry.ReplicateTime <= DateTime.UtcNow &&
                            entries.TryGetValue(entry.Key, out var record))
                        {
                            if (l == null)
                                l = new List<Task>();

                            using (slim.BeginWriteLock())
                            {
                                // schedule replication
                                l.Add(Task.Run(() => ReplicateAsync(entry, cancellationToken)));

                                // update to next time
                                entry.ReplicateTime = DateTime.UtcNow + frequency;

                                // remove existing queue entry
                                if (record.RepQueueHandle != null)
                                    repQueue.Delete(record.RepQueueHandle);

                                // add new queue entry
                                repQueue.Add(ref record.RepQueueHandle, entry);
                            }
                        }
                    }

                    // wait for all our replicate events to finish
                    if (l != null)
                        await Task.WhenAll(l);
                }
                catch (Exception e)
                {
                    logger.LogError(e, "Unexpected exception occurred republishing stored values.");
                }

                await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken);
            }
        }

19 Source : AppHost.cs
with MIT License
from alethic

public void Run(CancellationToken cancellationToken = default)
        {
            Task.Run(() => RunAsync(cancellationToken)).Wait();
        }

19 Source : KUdpServer.cs
with MIT License
from alethic

public void OnReceive(Socket receive, Socket respond, SocketAsyncEventArgs args)
        {
            var source = new KIpEndpoint((IPEndPoint)args.RemoteEndPoint);
            logger.LogTrace("Received incoming packet of {Length} from {Endpoint}.", args.BytesTransferred, source);

            try
            {
                // no data found
                if (args.BytesTransferred == 0)
                    return;

                // some error occurred?
                if (args.SocketError != SocketError.Success)
                {
                    logger.LogError("Socket error while receiving UDP data: {SocketError}.", args.SocketError);
                    return;
                }

                // we only care about receive from events
                if (args.LastOperation != SocketAsyncOperation.ReceiveFrom &&
                    args.LastOperation != SocketAsyncOperation.ReceiveMessageFrom)
                {
                    logger.LogError("Unxpected operation while receiving UDP data: {LastOperation}.", args.LastOperation);
                    return;
                }

                // deserialize message sequence
                var packet = serializer.Read(new ReadOnlyMemory<byte>(args.Buffer, args.Offset, args.BytesTransferred), new KMessageContext<TNodeId>(formats.Select(i => i.ContentType)));
                if (packet.Format == null || packet.Sequence == null)
                {
                    logger.LogWarning("Invalid or empty packet.");
                    return;
                }

                Task.Run(async () =>
                {
                    try
                    {
                        logger.LogTrace("Decoded packet as {Format} from {Endpoint}.", packet.Format, source);
                        await OnReceiveAsync(receive, respond, source, packet, CancellationToken.None);
                    }
                    catch (Exception e)
                    {
                        logger.LogError(e, "Unhandled exception receiving UDP packet.");
                    }
                });
            }
            catch (Exception e)
            {
                logger.LogError(e, "Exception during UDP receive.");
            }
        }

19 Source : KStaticDiscovery.cs
with MIT License
from alethic

void OnEndpointsChanged(object sender, EventArgs args)
        {
            Task.Run(() => DiscoveryAsync(CancellationToken.None));
        }

19 Source : AcctUpsertTest.cs
with Apache License 2.0
from AlexandreDaSilva

private async Task DoUpserts()
        {
            var tasks = new List<Task>();

            foreach (var a in _accounts)
            {
                tasks.AddRange(Enumerable
                    .Range(0, 5)
                    .Select(_ => Task.Run(() => Upsert(a))));
            }

            await Task.WhenAll(tasks);
        }

19 Source : BankTest.cs
with Apache License 2.0
from AlexandreDaSilva

[Test]
        public async Task test_bank()
        {
            await CreateAccounts();

            var totalTask = Task.Run(() => RunTotalInLoop());

            var txnTask = Task.WhenAll(Enumerable.Range(0, 10)
                .Select(_ => Task.Run(() => TxnLoop())));

            if (!txnTask.Wait(1000 * 60 * 5))
            {
                Console.WriteLine("Timeout elapsed");
            }

            totalTask.Wait(1000 * 5);
        }

19 Source : ImageGalleryWindowViewModel.cs
with GNU General Public License v3.0
from alexdillon

private void UpdateSearchResults()
        {
            if (this.DeferSearchUpdating)
            {
                return;
            }

            foreach (var image in this.Images)
            {
                image.Dispose();
            }

            this.Images.Clear();
            this.LastShownMessageIndex = 0;

            var startDate = this.FilterStartDate;
            var endDate = (this.FilterEndDate == DateTime.MinValue) ? DateTime.Now : this.FilterEndDate.AddDays(1);

            var startDateUnix = ((DateTimeOffset)startDate).ToUnixTimeSeconds();
            var endDateUnix = ((DateTimeOffset)endDate).ToUnixTimeSeconds();

            IQueryable<Message> messagesFromMember;
            if (this.FilterMessagesFrom == null)
            {
                // Show messages from all chat members
                messagesFromMember = this.CacheSession.CacheForGroupOrChat;
            }
            else
            {
                var userId = this.FilterMessagesFrom.UserId;
                if (string.IsNullOrEmpty(userId) && this.GroupChat is Chat chat)
                {
                    // In Chats, the OtherUser field doesn't have the UserId set from GroupMe's API...
                    userId = chat.Id;
                }

                messagesFromMember = this.CacheSession.CacheForGroupOrChat
                    .Where(m => m.UserId == userId);
            }

            this.MessagesWithAttachments = messagesFromMember
                .Where(m => m.CreatedAtUnixTime >= startDateUnix)
                .Where(m => m.CreatedAtUnixTime <= endDateUnix)
                .OrderByDescending(m => m.CreatedAtUnixTime);

            this.FilteredMessagesCount = this.MessagesWithAttachments.Count();

            Task.Run(this.LoadNextPage);
        }

19 Source : PaginatedMessagesControlViewModel.cs
with GNU General Public License v3.0
from alexdillon

private IEnumerable<Message> GetFromGroupMe(Message startAt, Message endAt)
        {
            return Task.Run(async () => await this.GetFromGroupMeAsync(startAt, endAt)).Result;
        }

19 Source : ChatsViewModel.cs
with GNU General Public License v3.0
from alexdillon

private async Task LoadGroupsAndChats(bool updateSuperIndexer = false)
        {
            await this.ReloadGroupsSem.WaitAsync();

            var persistContext = this.PersistManager.OpenNewContext();

            try
            {
                await this.GroupMeClient.GetGroupsAsync();
                await this.GroupMeClient.GetChatsAsync();

                var groupsAndChats = Enumerable.Concat<IMessageContainer>(this.GroupMeClient.Groups(), this.GroupMeClient.Chats());

                if (updateSuperIndexer)
                {
                    // Submit new Group and Chat listings to SuperIndexer to allow for background indexing if needed.
                    this.CacheManager.SuperIndexer.BeginAsyncTransaction(groupsAndChats);
                }

                foreach (var group in groupsAndChats)
                {
                    // check the last-read message status from peristant storage
                    var groupState = persistContext.GroupChatStates.FirstOrDefault(g => g.GroupOrChatId == group.Id);
                    if (groupState == null)
                    {
                        groupState = new GroupOrChatState()
                        {
                            GroupOrChatId = group.Id,
                            LastTotalMessageCount = group.TotalMessageCount,
                        };
                        persistContext.GroupChatStates.Add(groupState);
                    }

                    // Code to update the UI needs to be run on the Application Dispatcher
                    // This is typically the case, but Timer events from ReliabilityStateMachine for
                    // retry-callbacks will NOT run on the original thread.
                    var uiDispatcher = Ioc.Default.GetService<IUserInterfaceDispatchService>();
                    await uiDispatcher.InvokeAsync(() =>
                    {
                        // calculate how many new messages have been added since the group/chat was last read
                        var unreadMessages = group.TotalMessageCount - groupState.LastTotalMessageCount;

                        if (unreadMessages < 0)
                        {
                            // strange errors can occur when the Group Listing lags behind the
                            // actual group contents. If this occurs, cancel and reload the sidebar.
                            this.RetryTimer = this.ReliabilityStateMachine.GetRetryTimer(() => Task.Run(() => this.LoadGroupsAndChats()));
                            return;
                        }

                        var existingVm = this.AllGroupsChats.Items.FirstOrDefault(g => g.Id == group.Id);
                        if (existingVm == null)
                        {
                            // create a new GroupControl ViewModel for this Group
                            var vm = new GroupControlViewModel(group)
                            {
                                GroupSelected = new RelayCommand<GroupControlViewModel>((g) => this.OpenNewGroupChat(g)),
                                TotalUnreadCount = unreadMessages,
                            };
                            this.AllGroupsChats.Add(vm);
                        }
                        else
                        {
                            // Update the existing Group/Chat VM
                            existingVm.MessageContainer = group;
                            existingVm.TotalUnreadCount = unreadMessages;
                        }

                        var openChatGroup = this.AllChats.FirstOrDefault(g => g.Id == group.Id);
                        if (openChatGroup != null)
                        {
                            // chat is open and already receiving new messages, so mark all messages as "read"
                            existingVm.TotalUnreadCount = 0;
                            groupState.LastTotalMessageCount = openChatGroup.MessageContainer.TotalMessageCount;
                        }
                    });
                }

                await persistContext.SaveChangesAsync();
                this.PublishTotalUnreadCount();

                // if everything was successful, reset the reliability monitor
                this.ReliabilityStateMachine.Succeeded();
                this.RetryTimer?.Dispose();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"Exception in {nameof(this.LoadGroupsAndChats)} - {ex.Message}. Retrying...");
                this.RetryTimer = this.ReliabilityStateMachine.GetRetryTimer(() => Task.Run(() => this.LoadGroupsAndChats()));
            }
            finally
            {
                persistContext.Dispose();
                this.ReloadGroupsSem.Release();
            }
        }

19 Source : ChatsViewModel.cs
with GNU General Public License v3.0
from alexdillon

private void OpenNewGroupChat(GroupControlViewModel group, bool skipClose = false, MessageControlViewModel startReply = null)
        {
            if (this.ActiveGroupsChats.Any(g => g.Id == group.Id))
            {
                // this group or chat is already open, we just need to move it to the front
                var openGroup = this.ActiveGroupsChats.First(g => g.Id == group.Id);
                var indexOpenGroup = this.ActiveGroupsChats.IndexOf(openGroup);
                this.ActiveGroupsChats.Move(indexOpenGroup, 0);

                if (startReply != null)
                {
                    openGroup.InitiateReply.Execute(startReply);
                }
            }
            else if (this.ActiveMiniChats.Any(g => g.Id == group.Id))
            {
                // this chat is already open as a MiniChat, just copy it into the main UI
                var openGroup = this.ActiveMiniChats.First(g => g.Id == group.Id);
                this.ActiveGroupsChats.Insert(0, openGroup);
            }
            else
            {
                // open a new group or chat
                var groupContentsDisplay = new GroupContentsControlViewModel(group.MessageContainer, this.SettingsManager)
                {
                    CloseGroup = new RelayCommand<GroupContentsControlViewModel>(this.CloseChat),
                    CloseMiniChat = new RelayCommand<GroupContentsControlViewModel>(this.CloseMiniChat),
                    RegisterAsMiniChat = new RelayCommand<GroupContentsControlViewModel>(this.RegisterMiniChat),
                };

                groupContentsDisplay.ObservableForProperty(x => x.IsFocused)
                    .Subscribe(prop =>
                    {
                        group.IsHighlighted = prop.Value;
                    });

                this.ActiveGroupsChats.Insert(0, groupContentsDisplay);

                Task.Run(async () => await this.PushClient.SubscribeAsync(group.MessageContainer));

                // mark all messages as read
                this.MarkGroupChatAsRead(group);

                this.PublishTotalUnreadCount();

                if (startReply != null)
                {
                    groupContentsDisplay.InitiateReply.Execute(new MessageControlViewModel(startReply));
                }
            }

            if (!skipClose)
            {
                // Limit to three multi-chats at a time
                // But, only close a single chat. Users will not expect multiple
                // chats to close at once. This could occur if the user opened several chats in MiniBar mode,
                // and then switched back to regular mode.
                var maximumChats = this.MiniBarModeEnabled ? this.SettingsManager.UISettings.MaximumNumberOfMultiChatsMinibar : this.SettingsManager.UISettings.MaximumNumberOfMultiChatsNormal;
                if (this.ActiveGroupsChats.Count > maximumChats)
                {
                    var removeGroup = this.ActiveGroupsChats.Last();
                    this.PushClient.Unsubscribe(group.MessageContainer);

                    this.ActiveGroupsChats.Remove(removeGroup);
                }
            }

            this.SaveRestoreState();
        }

19 Source : ChatsViewModel.cs
with GNU General Public License v3.0
from alexdillon

async Task INotificationSink.GroupUpdated(LineMessageCreateNotification notification, IMessageContainer container)
        {
            this.CacheManager.SuperIndexer.BeginAsyncTransaction();

            _ = Task.Run(async () => await this.LoadGroupsAndChats(true));

            var groupVm = this.AllChats.FirstOrDefault(g => g.Id == container.Id);
            if (groupVm != null)
            {
                await groupVm.LoadNewMessages();
            }

            this.CacheManager.SuperIndexer.EndTransaction();
        }

19 Source : ChatsViewModel.cs
with GNU General Public License v3.0
from alexdillon

async Task INotificationSink.ChatUpdated(DirectMessageCreateNotification notification, IMessageContainer container)
        {
            _ = Task.Run(async () => await this.LoadGroupsAndChats(true));
            var chatVm = this.AllChats.FirstOrDefault(g => g.Id == container.Id);
            if (chatVm != null)
            {
                await chatVm.LoadNewMessages();
            }

            this.CacheManager.SuperIndexer.EndTransaction();
        }

19 Source : GroupContentsControlViewModel.cs
with GNU General Public License v3.0
from alexdillon

private void UpdateDisplay(ScrollViewer scrollViewer, ICollection<Message> messages)
        {
            if (messages.Count == 0)
            {
                return;
            }

            Avalonia.Threading.Dispatcher.UIThread.Post(() =>
            {
                // Run on UI thread since the ScrollViewer is being directly manipulated.
                double originalHeight = scrollViewer?.GetValue(ScrollViewer.VerticalScrollBarMaximumProperty) ?? 0.0;
                if (originalHeight != 0)
                {
                    // Prevent the At Top event from firing while we are adding new messages
                    scrollViewer.SetValue(ScrollViewer.VerticalScrollBarValueProperty, 1);
                }

                var maxTimeDifference = TimeSpan.FromMinutes(15);

                // Messages retrieved with the before_id parameter are returned in descending order
                // Reverse iterate through the messages collection to go newest->oldest
                for (int i = messages.Count - 1; i >= 0; i--)
                {
                    var msg = messages.ElementAt(i);

                    var oldMsg = this.Messages.Items.FirstOrDefault(m => m.Id == msg.Id);

                    if (oldMsg == null)
                    {
                        // add new message
                        var msgVm = new MessageControlViewModel(
                            msg,
                            showPreviewsOnlyForMultiImages: this.Settings.UISettings.ShowPreviewsForMultiImages);
                        this.Messages.Add(msgVm);

                        // add an inline timestamp if needed
                        if (msg.CreatedAtTime.Subtract(this.LastMarkerTime) > maxTimeDifference)
                        {
                            var messageId = long.Parse(msg.Id);
                            var timeStampId = (messageId - 1).ToString();

                            this.Messages.Add(new InlineTimestampControlViewModel(msg.CreatedAtTime, timeStampId, msgVm.DidISendIt));
                            this.LastMarkerTime = msg.CreatedAtTime;
                        }
                    }
                    else
                    {
                        // update an existing one if needed
                        oldMsg.Message = msg;
                    }
                }

                // process read receipt and sent receipts
                if (this.MessageContainer.ReadReceipt != null)
                {
                    // Remove old markers
                    var toRemove = this.Messages.Items.OfType<InlineReadSentMarkerControlViewModel>().ToList();
                    foreach (var marker in toRemove)
                    {
                        this.Messages.Remove(marker);
                    }

                    // Attach a "Read Receipt" if the read message is displayed.
                    var matchedMessage = this.Messages.Items.FirstOrDefault(m => m.Id == this.MessageContainer.ReadReceipt.MessageId);
                    if (matchedMessage != null)
                    {
                        var msgId = long.Parse(matchedMessage.Id);

                        var readMarker = new InlineReadSentMarkerControlViewModel(
                            this.MessageContainer.ReadReceipt.ReadAtTime,
                            true,
                            (msgId + 1).ToString(),
                            (matchedMessage as MessageControlViewModel).DidISendIt);

                        this.Messages.Add(readMarker);
                    }

                    // Attach a "Sent Receipt" to the last message confirmed sent by GroupMe
                    var me = this.MessageContainer.WhoAmI();
                    var lastSentMessage = this.Messages.Items
                        .OfType<MessageControlViewModel>()
                        .OrderByDescending(m => m.Id)
                        .FirstOrDefault(m => m.Message.UserId == me.Id);

                    if (lastSentMessage != null && lastSentMessage != matchedMessage)
                    {
                        var msgId = long.Parse(lastSentMessage.Id);

                        var sentMarker = new InlineReadSentMarkerControlViewModel(
                            lastSentMessage.Message.CreatedAtTime,
                            false,
                            (msgId + 1).ToString(),
                            (lastSentMessage as MessageControlViewModel).DidISendIt);

                        this.Messages.Add(sentMarker);
                    }

                    // Send a Read Receipt for the last message received
                    var lastReceivedMessage = this.Messages.Items
                        .OfType<MessageControlViewModel>()
                        .OrderByDescending(m => m.Id)
                        .FirstOrDefault(m => m.Message.UserId != me.Id);

                    if (lastReceivedMessage != null && this.MessageContainer is Chat c)
                    {
                        var result = Task.Run(async () => await c.SendReadReceipt(lastReceivedMessage.Message)).Result;
                    }
                }

                if (originalHeight != 0)
                {
                    // Calculate the offset where the last message the user was looking at is
                    // Scroll back to there so new messages appear on top, above screen
                    scrollViewer?.GetObservable(ScrollViewer.VerticalScrollBarMaximumProperty).Take(2).Skip(1).Subscribe(newMax =>
                    {
                        double difference = newMax - originalHeight;
                        scrollViewer.SetValue(ScrollViewer.VerticalScrollBarValueProperty, difference);
                    });
                }

                if (messages.Count > 0)
                {
                    this.FirstDisplayedMessage = messages.Last();
                }
            });
        }

19 Source : PathFilterHelper.cs
with MIT License
from alexis-

public static async Task<IEnumerable<FileInfo>> TraverseDirectoryWithFilterAsync(
      string rootDirPath,
      HashSet<PathFilter> filterIncludes,
      HashSet<PathFilter> filterExcludes,
      traverseFSFileAdded callback)
    {
      return await Task.Run(
        () => TraverseDirectoryWithFilter(
          rootDirPath,
          filterIncludes,
          filterExcludes,
          callback)
      );
    }

19 Source : EditSnapshotRuleForm.cs
with MIT License
from alexis-

private string ComputeMaxSnapshotCount(SnapshotRule rule)
    {
      var nextFireTime = rule.GetNextFireTime(DateTimeOffset.Now.AddSeconds(-1));

      if (!nextFireTime.HasValue)
        return "0";

      var lastFireTime = nextFireTime.Value.AddSeconds(rule.GetLifeTimeSeconds());

      CancellationTokenSource cancelSrc = new CancellationTokenSource();
      CancellationToken cancelToken = cancelSrc.Token;

      Task<int> computeTask =
        Task.Run(() => rule.GetFireCountBetween(nextFireTime.Value, lastFireTime, cancelToken));

      try
      {
        cancelSrc.CancelAfter(1000);
        computeTask.Wait(cancelToken);

        return computeTask.Result.ToString();
      }
      catch (OperationCanceledException)
      {
        return "(timeout: too many)";
      }
    }

See More Examples