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

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

8135 Examples 7

19 Source : CelesteNetServer.cs
with MIT License
from 0x0ade

public void BroadcastAsync(DataType data) {
            DataInternalBlob blob = new(Data, data);
            using (ConLock.R())
                foreach (CelesteNetConnection con in Connections) {
                    Task.Run(() => {
                        try {
                            con.Send(blob);
                        } catch (Exception e) {
                            // Whoops, it probably wasn't important anyway.
                            Logger.Log(LogLevel.DEV, "main", $"Broadcast (async) failed:\n{data}\n{con}\n{e}");
                        }
                    });
                }
        }

19 Source : ChatModule.cs
with MIT License
from 0x0ade

public void Handle(CelesteNetConnection? con, DataChat msg) {
            if (PrepareAndLog(con, msg) == null)
                return;

            if ((!msg.CreatedByServer || msg.Player == null) && msg.Text.StartsWith(Settings.CommandPrefix)) {
                if (msg.Player != null) {
                    // Player should at least receive msg ack.
                    msg.Color = Settings.ColorCommand;
                    msg.Target = msg.Player;
                    ForceSend(msg);
                }

                // TODO: Improve or rewrite. This comes from GhostNet, which adopted it from disbot (0x0ade's C# Discord bot).

                ChatCMDEnv env = new(this, msg);

                string cmdName = env.FullText.Substring(Settings.CommandPrefix.Length);
                cmdName = cmdName.Split(ChatCMD.NameDelimiters)[0].ToLowerInvariant();
                if (cmdName.Length == 0)
                    return;

                ChatCMD? cmd = Commands.Get(cmdName);
                if (cmd != null) {
                    env.Cmd = cmd;
                    Task.Run(() => {
                        try {
                            cmd.ParseAndRun(env);
                        } catch (Exception e) {
                            env.Error(e);
                        }
                    });

                } else {
                    env.Send($"Command {cmdName} not found!", color: Settings.ColorError);
                }

                return;
            }

            if (msg.Player != null && Server.PlayersByID.TryGetValue(msg.Player.ID, out CelesteNetPlayerSession? session) &&
                Server.UserData.Load<UserChatSettings>(session.UID).AutoChannelChat) {
                msg.Target = msg.Player;
                Commands.Get<ChatCMDChannelChat>().ParseAndRun(new ChatCMDEnv(this, msg));
                return;
            }

            Server.BroadcastAsync(msg);
        }

19 Source : DataContext.cs
with MIT License
from 0x0ade

public Action WaitFor<T>(int timeout, DataFilter<T> cb, Action? cbTimeout = null) where T : DataType<T> {
            object key = new();

            DataHandler? wrap = null;
            wrap = RegisterHandler<T>((con, data) => {
                lock (key) {
                    if (wrap == null || !cb(con, data))
                        return;
                    UnregisterHandler(typeof(T), wrap);
                    wrap = null;
                }
            });

            if (timeout > 0)
                Task.Run(async () => {
                    await Task.Delay(timeout);
                    lock (key) {
                        if (wrap == null)
                            return;
                        try {
                            UnregisterHandler(typeof(T), wrap);
                            wrap = null;
                            cbTimeout?.Invoke();
                        } catch (Exception e) {
                            Logger.Log(LogLevel.CRI, "data", $"Error in WaitFor timeout callback:\n{typeof(T).FullName}\n{cb}\n{e}");
                        }
                    }
                });

            return () => UnregisterHandler(typeof(T), wrap);
        }

19 Source : DataContext.cs
with MIT License
from 0x0ade

protected void Handle(CelesteNetConnection con, Type? type, DataType? data) {
            if (type == null || data == null)
                return;

            if ((data.DataFlags & DataFlags.Taskable) == DataFlags.Taskable) {
                Task.Run(() => {
                    try {
                        HandleInner(con, type, data);
                    } catch (Exception e) {
                        Logger.Log(LogLevel.CRI, "data-task", $"Failed handling data in task:\n{con}\n{type.FullName}\n{e}");
                    }
                });
                return;
            }

            HandleInner(con, type, data);
        }

19 Source : WebUserManager.cs
with Apache License 2.0
from 0xFireball

public async Task<RegisteredUser> FindUserByUsernameAsync(string username)
        {
            return await Task.Run(() =>
            {
                RegisteredUser storedUserRecord = null;
                var db = new DatabaseAccessService().OpenOrCreateDefault();
                var registeredUsers =
                    db.GetCollection<RegisteredUser>(DatabaseAccessService.UsersCollectionDatabaseKey);
                var userRecord = registeredUsers.FindOne(u => u.Username == username);
                storedUserRecord = userRecord;

                return storedUserRecord;
            });
        }

19 Source : WebUserManager.cs
with Apache License 2.0
from 0xFireball

public async Task<bool> UpdateUserInDatabaseAsync(RegisteredUser user)
        {
            var result = false;
            await Task.Run(() =>
            {
                var db = new DatabaseAccessService().OpenOrCreateDefault();
                var registeredUsers =
                    db.GetCollection<RegisteredUser>(DatabaseAccessService.UsersCollectionDatabaseKey);
                using (var trans = db.BeginTrans())
                {
                    result = registeredUsers.Update(user);
                    trans.Commit();
                }
            });
            return result;
        }

19 Source : WebUserManager.cs
with Apache License 2.0
from 0xFireball

public async Task<bool> CheckPreplacedwordAsync(string preplacedword, RegisteredUser user)
        {
            var ret = false;
            var lockEntry = ServerContext.ServiceTable.GetOrCreate(user.Username).UserLock;
            await lockEntry.WithConcurrentReadAsync(Task.Run(() =>
            {
                //Calculate hash and compare
                var cryptoHelper = new AuthCryptoHelper(user.Crypto.Conf);
                var pwKey =
                    cryptoHelper.CalculateUserPreplacedwordHash(preplacedword, user.Crypto.Salt);
                ret = StructuralComparisons.StructuralEqualityComparer.Equals(pwKey, user.Crypto.Key);
            }));
            return ret;
        }

19 Source : WebUserManager.cs
with Apache License 2.0
from 0xFireball

public async Task RemoveUserAsync(string username)
        {
            await Task.Run(() =>
            {
                var db = new DatabaseAccessService().OpenOrCreateDefault();
                var registeredUsers =
                    db.GetCollection<RegisteredUser>(DatabaseAccessService.UsersCollectionDatabaseKey);
                using (var trans = db.BeginTrans())
                {
                    registeredUsers.Delete(u => u.Username == username);
                    trans.Commit();
                }
            });
        }

19 Source : WebUserManager.cs
with Apache License 2.0
from 0xFireball

public async Task ChangeUserPreplacedwordAsync(RegisteredUser user, string newPreplacedword)
        {
            var lockEntry = ServerContext.ServiceTable.GetOrCreate(user.Username).UserLock;
            await lockEntry.WithExclusiveWriteAsync(Task.Run(async () =>
            {
                // Recompute preplacedword crypto
                var cryptoConf = PreplacedwordCryptoConfiguration.CreateDefault();
                var cryptoHelper = new AuthCryptoHelper(cryptoConf);
                var pwSalt = cryptoHelper.GenerateSalt();
                var encryptedPreplacedword =
                    cryptoHelper.CalculateUserPreplacedwordHash(newPreplacedword, pwSalt);
                user.Crypto = new ItemCrypto
                {
                    Salt = pwSalt,
                    Conf = cryptoConf,
                    Key = encryptedPreplacedword
                };
                // Save changes
                await UpdateUserInDatabaseAsync(user);
            }));
        }

19 Source : WebUserManager.cs
with Apache License 2.0
from 0xFireball

public async Task GenerateNewApiKeyAsync(RegisteredUser user)
        {
            var lockEntry = ServerContext.ServiceTable.GetOrCreate(user.Username).UserLock;
            await lockEntry.WithExclusiveWriteAsync(Task.Run(async () =>
            {
                // Recompute key
                user.ApiKey = StringUtils.SecureRandomString(AuthCryptoHelper.DefaultApiKeyLength);
                await UpdateUserInDatabaseAsync(user);
            }));
        }

19 Source : WebUserManager.cs
with Apache License 2.0
from 0xFireball

public async Task<IEnumerable<RegisteredUser>> GetAllUsersAsync()
        {
            return await Task.Run(() =>
            {
                var db = new DatabaseAccessService().OpenOrCreateDefault();
                var registeredUsers =
                    db.GetCollection<RegisteredUser>(DatabaseAccessService.UsersCollectionDatabaseKey);
                return registeredUsers.FindAll();
            });
        }

19 Source : StoredFilesManager.cs
with Apache License 2.0
from 0xFireball

public async Task<StoredFile> RegisterStoredFileAsync(string ownerName, string fileName, string userPath, string identifier,
            long fileSize)
        {
            return await Task.Run(() =>
            {
                var userDatabaseLock = ServerContext.ServiceTable.GetOrCreate(ownerName).UserLock;
                userDatabaseLock.ObtainExclusiveWrite();
                var db = new DatabaseAccessService().OpenOrCreateDefault();
                var storedFiles = db.GetCollection<StoredFile>(DatabaseAccessService.StoredFilesCollectionDatabaseKey);
                var result = new StoredFile
                {
                    Name = fileName,
                    Identifier = identifier,
                    FileSize = fileSize,
                    OwnerUsername = ownerName,
                    ParentDirPath = userPath
                };
                using (var trans = db.BeginTrans())
                {
                    storedFiles.Insert(result);
                    trans.Commit();
                }
                userDatabaseLock.ReleaseExclusiveWrite();

                // Index the database
                storedFiles.EnsureIndex(x => x.Identifier);
                return result;
            });
        }

19 Source : StoredFilesManager.cs
with Apache License 2.0
from 0xFireball

public async Task<StoredFile> GetStoredFileByIdentifierAsync(string id)
        {
            return await Task.Run(() =>
            {
                var db = new DatabaseAccessService().OpenOrCreateDefault();
                var storedFiles = db.GetCollection<StoredFile>(DatabaseAccessService.StoredFilesCollectionDatabaseKey);
                return storedFiles
                    .FindOne(x => x.Identifier == id);
            });
        }

19 Source : StoredFilesManager.cs
with Apache License 2.0
from 0xFireball

public async Task<IEnumerable<StoredFile>> GetStoredFilesByUserAsync(RegisteredUser user)
        {
            return await Task.Run(() =>
            {
                var db = new DatabaseAccessService().OpenOrCreateDefault();
                var storedFiles = db.GetCollection<StoredFile>(DatabaseAccessService.StoredFilesCollectionDatabaseKey);
                return storedFiles
                    .Find(x => x.OwnerUsername == user.Username)
                    .OrderByDescending(x => x.UploadedDate);
            });
        }

19 Source : StoredFilesManager.cs
with Apache License 2.0
from 0xFireball

public async Task UnregisterStoredFileAsync(string fileId)
        {
            await Task.Run(() =>
            {
                var db = new DatabaseAccessService().OpenOrCreateDefault();
                var storedFiles = db.GetCollection<StoredFile>(DatabaseAccessService.StoredFilesCollectionDatabaseKey);
                using (var trans = db.BeginTrans())
                {
                    storedFiles.Delete(x => x.Identifier == fileId);
                    trans.Commit();
                }
                storedFiles.EnsureIndex(x => x.Identifier);
            });
        }

19 Source : StoredFilesManager.cs
with Apache License 2.0
from 0xFireball

public async Task NukeAllFilesAsync(RegisteredUser user)
        {
            await Task.Run(() =>
            {
                var db = new DatabaseAccessService().OpenOrCreateDefault();
                var storedFiles = db.GetCollection<StoredFile>(DatabaseAccessService.StoredFilesCollectionDatabaseKey);
                using (var trans = db.BeginTrans())
                {
                    storedFiles
                        .Delete(x => x.OwnerUsername == user.Username);
                    trans.Commit();
                }
                storedFiles.EnsureIndex(x => x.Identifier);
            });
        }

19 Source : StoredFilesManager.cs
with Apache License 2.0
from 0xFireball

public async Task<bool> UpdateStoredFileInDatabaseAsync(StoredFile currentFile)
        {
            return await Task.Run(() =>
            {
                bool result;
                var db = new DatabaseAccessService().OpenOrCreateDefault();
                var storedFiles =
                    db.GetCollection<StoredFile>(DatabaseAccessService.StoredFilesCollectionDatabaseKey);
                using (var trans = db.BeginTrans())
                {
                    result = storedFiles.Update(currentFile);
                    trans.Commit();
                }
                return result;
            });
        }

19 Source : ServerMessageHandler.cs
with MIT License
from 1100100

public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            Task.Run(async () =>
            {
                var msg = message;
                if (!(msg is TransportMessage<IInvokeMessage> transportMessage))
                    throw new ArgumentNullException(nameof(message));
                try
                {
                    if (Logger.IsEnabled(LogLevel.Trace))
                        Logger.LogTrace($"The server received the message:\nCurrent node:{ServerSettings}\nRoute:{transportMessage.Body.Route}\nMessage id:{transportMessage.Id}\nArgs:{Codec.ToJson(transportMessage.Body.Args)}\nMeta:{Codec.ToJson(transportMessage.Body.Meta)}\n\n");
                    var result = await ServiceFactory.InvokeAsync(transportMessage.Body.Route, transportMessage.Body.Args,
                        transportMessage.Body.Meta);
                    await context.WriteAndFlushAsync(new TransportMessage<IServiceResult>
                    {
                        Id = transportMessage.Id,
                        Body = result
                    });
                }
                catch (NotFoundRouteException e)
                {
                    Logger.LogError(e, $"The server message processing failed:{e.Message}.\nCurrent node:{ServerSettings}\nRoute:{transportMessage.Body.Route}\nMessage id:{transportMessage.Id}\n\n");
                    await context.WriteAndFlushAsync(new TransportMessage<IServiceResult>
                    {
                        Id = transportMessage.Id,
                        Body = new ServiceResult(e.Message, RemotingStatus.NotFound)
                    });
                }
                catch (Exception e)
                {
                    Logger.LogError(e, $"The server message processing failed:{e.Message}.\nCurrent node:{ServerSettings}\nRoute:{transportMessage.Body.Route}\nMessage id:{transportMessage.Id}\n\n");
                    await context.WriteAndFlushAsync(new TransportMessage<IServiceResult>
                    {
                        Id = transportMessage.Id,
                        Body = new ServiceResult(e.Message, RemotingStatus.Error)
                    });
                }
            });
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v3.0
from 1RedOne

private async void CreateClientsButton_Click(object sender, RoutedEventArgs e)
        {
            DeviceExpander.IsExpanded = true;

            string BaseName = NewClientName.Text;
            int CountOfMachines = (Int32.TryParse(NumberOfClients.Text, out int unUsed)) ? Int32.Parse(NumberOfClients.Text) : 1;
            int BeginningWith = (!StartingNumber.Text.Length.Equals(0)) ? Int32.Parse(StartingNumber.Text) : 0;
            List<String> DeviceList = new List<string>();
            int current = 0;
            object lockCurrent = new object();
            var progress = new Progress<int>(_ => IdCounter++) as IProgress<int>;

            for (int i = BeginningWith; i <= CountOfMachines; i++)
            {
                string ThisClient = BaseName + i;
                DeviceList.Add(ThisClient);
            }

            var myTask = Task.Run(() =>
            {
                Parallel.For(0, DeviceList.Count,
                    new ParallelOptions { MaxDegreeOfParallelism = MaxThreads },
                    (ii, loopState) =>
                    {
                        int thisCurrent = 0;
                        lock (lockCurrent)
                        {
                            thisCurrent = current;
                            current++;
                        }
                        string device = DeviceList[thisCurrent];
                        Device ThisDevice = new Device() { Name = device, Status = "Starting...", ImageSource = "Images\\step01.png", ProcessProgress = 10 };
                        Devices.Add(ThisDevice);
                        int thisIndex = Devices.IndexOf(ThisDevice);
                        RegisterClient(thisIndex);

                        progress.Report(0);
                    });
            });

            await myTask;
        }

19 Source : CSRedisClientStringTests.cs
with MIT License
from 2881099

[Fact]
		public void Get() {
            var testss = rds.StartPipe(a =>
            {
                a.Get<int?>("1");
                a.Get<int?>("2");
                a.Get("3");
                a.Get<long>("4");
            });

            Task.Run(async() => {
                var key = "TestGet_null";
                await rds.SetAsync(key, base.Null);
                replacedert.Equal((await rds.GetAsync(key))?.ToString() ?? "", base.Null?.ToString() ?? "");

                key = "TestGet_string";
                await rds.SetAsync(key, base.String);
                replacedert.Equal(await rds.GetAsync(key), base.String);

                key = "TestGet_bytes";
                await rds.SetAsync(key, base.Bytes);
                replacedert.Equal(await rds.GetAsync<byte[]>(key), base.Bytes);

                key = "TestGet_clreplaced";
                await rds.SetAsync(key, base.Clreplaced);
                replacedert.Equal((await rds.GetAsync<TestClreplaced>(key))?.ToString(), base.Clreplaced.ToString());

                key = "TestGet_clreplacedArray";
                await rds.SetAsync(key, new[] { base.Clreplaced, base.Clreplaced });
                replacedert.Equal(2, rds.Get<TestClreplaced[]>(key)?.Length);
                replacedert.Equal((await rds.GetAsync<TestClreplaced[]>(key))?.First().ToString(), base.Clreplaced.ToString());
                replacedert.Equal((await rds.GetAsync<TestClreplaced[]>(key))?.Last().ToString(), base.Clreplaced.ToString());
            }).Wait();

			
		}

19 Source : Program.cs
with MIT License
from 2881099

static void Main(string[] args)
        {
            RedisHelper.Initialization(new CSRedis.CSRedisClient("127.0.0.1:6379,asyncPipeline=true,preheat=100,poolsize=100"));
            cli.Set("TestMGet_null1", "");
            RedisHelper.Set("TestMGet_null1", "");
            sedb.StringSet("TestMGet_string1", String);
            ThreadPool.SetMinThreads(10001, 10001);
            Stopwatch sw = new Stopwatch();
            var tasks = new List<Task>();
            var results = new ConcurrentQueue<string>();

            cli.FlushDb();
            while (results.TryDequeue(out var del)) ;
            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                sedb.StringSet(tmp, String);
                var val = sedb.StringGet(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("StackExchange(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    sedb.StringSet(tmp, String);
                    var val = sedb.StringGet(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("StackExchange(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            Task.Run(async () =>
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    await sedb.StringSetAsync(tmp, String);
                    var val = await sedb.StringGetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }).Wait();
            sw.Stop();
            Console.WriteLine("StackExchangeAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(async () =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    await sedb.StringSetAsync(tmp, String);
                    var val = await sedb.StringGetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("StackExchangeAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();


            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                cli.Set(tmp, String);
                var val = cli.Get(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("FreeRedis(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    cli.Set(tmp, String);
                    var val = cli.Get(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("FreeRedis(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            Task.Run(async () =>
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    await cli.SetAsync(tmp, String);
                    var val = await cli.GetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }).Wait();
            sw.Stop();
            Console.WriteLine("FreeRedisAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            //FreeRedis.Internal.AsyncRedisSocket.sb.Clear();
            //FreeRedis.Internal.AsyncRedisSocket.sw.Start();
            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(async () =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    await cli.SetAsync(tmp, String);
                    var val = await cli.GetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            //var sbstr = FreeRedis.Internal.AsyncRedisSocket.sb.ToString()
            //sbstr = sbstr + sbstr.Split("\r\n").Length + "条消息 ;
            Console.WriteLine("FreeRedisAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            using (var pipe = cli.StartPipe())
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    pipe.Set(tmp, String);
                    var val = pipe.Get(tmp);
                }
                var vals = pipe.EndPipe();
                for (var a = 1; a < 200000; a += 2)
                {
                    var val = vals[a].ToString();
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }
            sw.Stop();
            Console.WriteLine("FreeRedisPipeline(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            //sw.Reset();
            //sw.Start();
            //for (var a = 0; a < 100000; a++)
            //    cli.Call(new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String));
            //sw.Stop();
            //Console.WriteLine("FreeRedis2: " + sw.ElapsedMilliseconds + "ms");
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            //sw.Reset();
            //sw.Start();
            //for (var a = 0; a < 100000; a++)
            //{
            //    using (var rds = cli.GetTestRedisSocket())
            //    {
            //        var cmd = new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String);
            //        rds.Write(cmd);
            //        cmd.Read<string>();
            //    }
            //}
            //sw.Stop();
            //Console.WriteLine("FreeRedis4: " + sw.ElapsedMilliseconds + "ms");
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();


            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                RedisHelper.Set(tmp, String);
                var val = RedisHelper.Get(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("CSRedisCore(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    RedisHelper.Set(tmp, String);
                    var val = RedisHelper.Get(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("CSRedisCore(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            Task.Run(async () =>
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    await RedisHelper.SetAsync(tmp, String);
                    var val = await RedisHelper.GetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }).Wait();
            sw.Stop();
            Console.WriteLine("CSRedisCoreAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(async () =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    await RedisHelper.SetAsync(tmp, String);
                    var val = await RedisHelper.GetAsync(tmp);
                    //if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("CSRedisCoreAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            while (results.TryDequeue(out var del)) ;
            cli.FlushDb();
        }

19 Source : CSRedisClientHashTests.cs
with MIT License
from 2881099

[Fact]
		public void HGetAll()
		{
			replacedert.True(rds.HMSet("TestHGetAll", "string1", base.String, "bytes1", base.Bytes, "clreplaced1", base.Clreplaced, "clreplaced1array", new[] { base.Clreplaced, base.Clreplaced }));
			replacedert.Equal(4, rds.HGetAll("TestHGetAll").Count);
			replacedert.Equal(base.String, rds.HGetAll("TestHGetAll")["string1"]);
			replacedert.Equal(Encoding.UTF8.GetString(base.Bytes), rds.HGetAll("TestHGetAll")["bytes1"]);
			replacedert.Equal(base.Clreplaced.ToString(), rds.HGetAll("TestHGetAll")["clreplaced1"]);

			Task.Run(async () =>
			{
				var test = await rds.HGetAllAsync("TestHGetAll");

				rds.Set("TestHGetAll2", "1");
				try
				{
					var test2 = await rds.HGetAllAsync("TestHGetAll2");
				}
				catch
				{

				}

				for (var a = 0; a < 1000; a++)
					test = await rds.HGetAllAsync("TestHGetAll");
			}).Wait();
		}

19 Source : CSRedisClientLockTests.cs
with MIT License
from 2881099

[Fact]
		public void Lock1() {
			var tasks = new Task[4];
			for (var a = 0; a < tasks.Length; a++)
				tasks[a] = Task.Run(() => {
					var lk = rds.Lock("testlock1", 10);
					Thread.CurrentThread.Join(1000);
					replacedert.True(lk.Unlock());
				});
			Task.WaitAll(tasks);
		}

19 Source : Program.cs
with MIT License
from 2881099

static void Main(string[] args)
        {

            sedb.StringSet("key1", (string)null);

            var val111 = sedb.StringGet("key1");














            RedisHelper.Initialization(new CSRedis.CSRedisClient("127.0.0.1:6379,asyncPipeline=true,preheat=100,poolsize=100"));
            cli.Set("TestMGet_null1", "");
            RedisHelper.Set("TestMGet_null1", "");
            sedb.StringSet("TestMGet_string1", String);
            ThreadPool.SetMinThreads(10001, 10001);
            Stopwatch sw = new Stopwatch();
            var tasks = new List<Task>();
            var results = new ConcurrentQueue<string>();

            cli.FlushDb();
            results.Clear();
            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                sedb.StringSet(tmp, String);
                var val = sedb.StringGet(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("StackExchange(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    sedb.StringSet(tmp, String);
                    var val = sedb.StringGet(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("StackExchange(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            Task.Run(async () =>
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    await sedb.StringSetAsync(tmp, String);
                    var val = await sedb.StringGetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }).Wait();
            sw.Stop();
            Console.WriteLine("StackExchangeAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(async () =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    await sedb.StringSetAsync(tmp, String);
                    var val = await sedb.StringGetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("StackExchangeAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            results.Clear();
            cli.FlushDb();


            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                cli.Set(tmp, String);
                var val = cli.Get(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("FreeRedis(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    cli.Set(tmp, String);
                    var val = cli.Get(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("FreeRedis(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            //sw.Reset();
            //sw.Start();
            //Task.Run(async () =>
            //{
            //    for (var a = 0; a < 100000; a++)
            //    {
            //        var tmp = Guid.NewGuid().ToString();
            //        await cli.SetAsync(tmp, String);
            //        var val = await cli.GetAsync(tmp);
            //        if (val != String) throw new Exception("not equal");
            //        results.Enqueue(val);
            //    }
            //}).Wait();
            //sw.Stop();
            //Console.WriteLine("FreeRedisAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            //tasks.Clear();
            //results.Clear();
            //cli.FlushDb();

            //FreeRedis.Internal.AsyncRedisSocket.sb.Clear();
            //FreeRedis.Internal.AsyncRedisSocket.sw.Start();
            //sw.Reset();
            //sw.Start();
            //tasks = new List<Task>();
            //for (var a = 0; a < 100000; a++)
            //{
            //    tasks.Add(Task.Run(async () =>
            //    {
            //        var tmp = Guid.NewGuid().ToString();
            //        await cli.SetAsync(tmp, String);
            //        var val = await cli.GetAsync(tmp);
            //        if (val != String) throw new Exception("not equal");
            //        results.Enqueue(val);
            //    }));
            //}
            //Task.WaitAll(tasks.ToArray());
            //sw.Stop();
            ////var sbstr = FreeRedis.Internal.AsyncRedisSocket.sb.ToString()
            ////sbstr = sbstr + sbstr.Split("\r\n").Length + "条消息 ;
            //Console.WriteLine("FreeRedisAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            //tasks.Clear();
            //results.Clear();
            //cli.FlushDb();

            sw.Reset();
            sw.Start();
            using (var pipe = cli.StartPipe())
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    pipe.Set(tmp, String);
                    var val = pipe.Get(tmp);
                }
                var vals = pipe.EndPipe();
                for (var a = 1; a < 200000; a += 2)
                {
                    var val = vals[a].ToString();
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }
            sw.Stop();
            Console.WriteLine("FreeRedisPipeline(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            //sw.Reset();
            //sw.Start();
            //for (var a = 0; a < 100000; a++)
            //    cli.Call(new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String));
            //sw.Stop();
            //Console.WriteLine("FreeRedis2: " + sw.ElapsedMilliseconds + "ms");
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            //sw.Reset();
            //sw.Start();
            //for (var a = 0; a < 100000; a++)
            //{
            //    using (var rds = cli.GetTestRedisSocket())
            //    {
            //        var cmd = new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String);
            //        rds.Write(cmd);
            //        cmd.Read<string>();
            //    }
            //}
            //sw.Stop();
            //Console.WriteLine("FreeRedis4: " + sw.ElapsedMilliseconds + "ms");
            tasks.Clear();
            results.Clear();
            cli.FlushDb();


            sw.Reset();
            sw.Start();
            for (var a = 0; a < 100000; a++)
            {
                var tmp = Guid.NewGuid().ToString();
                RedisHelper.Set(tmp, String);
                var val = RedisHelper.Get(tmp);
                if (val != String) throw new Exception("not equal");
                results.Enqueue(val);
            }
            sw.Stop();
            Console.WriteLine("CSRedisCore(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    RedisHelper.Set(tmp, String);
                    var val = RedisHelper.Get(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("CSRedisCore(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            Task.Run(async () =>
            {
                for (var a = 0; a < 100000; a++)
                {
                    var tmp = Guid.NewGuid().ToString();
                    await RedisHelper.SetAsync(tmp, String);
                    var val = await RedisHelper.GetAsync(tmp);
                    if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }
            }).Wait();
            sw.Stop();
            Console.WriteLine("CSRedisCoreAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
            tasks.Clear();
            results.Clear();
            cli.FlushDb();

            sw.Reset();
            sw.Start();
            tasks = new List<Task>();
            for (var a = 0; a < 100000; a++)
            {
                tasks.Add(Task.Run(async () =>
                {
                    var tmp = Guid.NewGuid().ToString();
                    await RedisHelper.SetAsync(tmp, String);
                    var val = await RedisHelper.GetAsync(tmp);
                    //if (val != String) throw new Exception("not equal");
                    results.Enqueue(val);
                }));
            }
            Task.WaitAll(tasks.ToArray());
            sw.Stop();
            Console.WriteLine("CSRedisCoreAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
            tasks.Clear();
            results.Clear();
            cli.FlushDb();
        }

19 Source : CodeGenerate.cs
with MIT License
from 2881099

public async Task<string> Setup(Models.TaskBuild task)
        {



            try
            {
                var paths = await Task.Run(() =>
                 {

                     var config = new TemplateServiceConfiguration();
                     config.EncodedStringFactory = new RawStringFactory();
                     var service = RazorEngineService.Create(config);
                     Engine.Razor = service;


                     ///本次要操作的数据库
                     var dataBases = task.TaskBuildInfos.Where(a => a.Level == 1).ToList();

                     string path = string.Empty;

                     foreach (var db in dataBases)
                     {
                         //创建数据库连接
                         using (IFreeSql fsql = new FreeSql.FreeSqlBuilder()
                        .UseConnectionString(db.DataBaseConfig.DataType, db.DataBaseConfig.ConnectionStrings)
                        .Build())
                         {

                             //取指定数据库信息
                             var tables = fsql.DbFirst.GetTablesByDatabase(db.Name);
							 var outputTables = tables;

                             //是否有指定表
                             var uTables = task.TaskBuildInfos.Where(a => a.Level > 1).Select(a => a.Name).ToArray();
                             if (uTables.Length > 0)
                                 //过滤不要的表
                                 outputTables = outputTables.Where(a => uTables.Contains(a.Name)).ToList();

                             //根据用户设置组装生成路径并验证目录是否存在
                             path = $"{task.GeneratePath}\\{db.Name}";
                             if (!Directory.Exists(path))
                                 Directory.CreateDirectory(path);

							 var razorId = Guid.NewGuid().ToString("N");
							 Engine.Razor.Compile(task.Templates.Code, razorId);
                             //开始生成操作
                             foreach (var table in outputTables)
                             {
								 var sw = new StringWriter();
								 var model = new RazorModel(fsql, task, tables, table);
								 Engine.Razor.Run(razorId, sw, null, model);
 

                                 StringBuilder plus = new StringBuilder();
                                 plus.AppendLine("//------------------------------------------------------------------------------");
                                 plus.AppendLine("// <auto-generated>");
                                 plus.AppendLine("//     此代码由工具生成。");
                                 plus.AppendLine("//     运行时版本:" + Environment.Version.ToString());
                                 plus.AppendLine("//     Website: http://www.freesql.net");
                                 plus.AppendLine("//     对此文件的更改可能会导致不正确的行为,并且如果");
                                 plus.AppendLine("//     重新生成代码,这些更改将会丢失。");
                                 plus.AppendLine("// </auto-generated>");
                                 plus.AppendLine("//------------------------------------------------------------------------------");

                                 plus.Append(sw.ToString());

                                 plus.AppendLine();
                                 File.WriteAllText($"{path}\\{task.FileName.Replace("{name}", model.GetCsName(table.Name))}", plus.ToString());
                             }
                         }
                     }
                     return path;
                 });

                Process.Start(paths);
                return "生成成功";
            }
            catch (Exception ex)
            {
                return "生成时发生异常,请检查模版代码.";
            }


        }

19 Source : CodeGenerate.cs
with MIT License
from 2881099

public async Task<string> Setup(TaskBuild taskBuild, List<DbTableInfo> outputTables)
        {
            try
            {
                var paths = await Task.Run(() =>
                {
                    var config = new TemplateServiceConfiguration();
                    config.EncodedStringFactory = new RawStringFactory();
                    Engine.Razor = RazorEngineService.Create(config);

                    string path = string.Empty;


                    foreach (var templatesPath in taskBuild.Templates)
                    {
                        path = $"{taskBuild.GeneratePath}\\{taskBuild.DbName}\\{templatesPath.Replace(".tpl", "").Trim()}";
                        if (!Directory.Exists(path)) Directory.CreateDirectory(path);

                        var razorId = Guid.NewGuid().ToString("N");
                        var html = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "Templates", templatesPath));
                        Engine.Razor.Compile(html, razorId);
                        //开始生成操作
                        foreach (var table in outputTables)
                        {
                            var sw = new StringWriter();
                            var model = new RazorModel(taskBuild, outputTables, table);
                            Engine.Razor.Run(razorId, sw, null, model);
                            StringBuilder plus = new StringBuilder();
                            plus.AppendLine("//------------------------------------------------------------------------------");
                            plus.AppendLine("// <auto-generated>");
                            plus.AppendLine("//     此代码由工具生成。");
                            plus.AppendLine("//     运行时版本:" + Environment.Version.ToString());
                            plus.AppendLine("//     Website: http://www.freesql.net");
                            plus.AppendLine("//     对此文件的更改可能会导致不正确的行为,并且如果");
                            plus.AppendLine("//     重新生成代码,这些更改将会丢失。");
                            plus.AppendLine("// </auto-generated>");
                            plus.AppendLine("//------------------------------------------------------------------------------");
                            plus.Append(sw.ToString());
                            plus.AppendLine();
                            var outPath = $"{path}\\{taskBuild.FileName.Replace("{name}", model.GetCsName(table.Name))}";
                            if (!string.IsNullOrEmpty(taskBuild.RemoveStr))
                                outPath = outPath.Replace(taskBuild.RemoveStr, "").Trim();
                            File.WriteAllText(outPath, plus.ToString());
                        }
                    }
                    return path;
                });
                Process.Start(paths);
                return "生成成功";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"生成时发生异常,请检查模版代码: {ex.Message}.");
                return $"生成时发生异常,请检查模版代码: {ex.Message}.";
            }
        }

19 Source : Form1.cs
with MIT License
from 2881099

async void LoadDataInfo(Node node)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(a =>
            {
                frmLoading = new FrmLoading();
                frmLoading.ShowDialog();
            }));
            var res = await Task.Run(() =>
             {

                 if (node.Level == 1)
                 {
                     if (node.Nodes.Count >= 1) return 0;
                     node.Nodes.Clear();
                     var list = G.GetDatabases(node.DataKey, node.TagString);
                     var nodes = list.Select(a => new Node(a)
                     {
                         Image = Properties.Resources._base,
                         DataKey = node.DataKey,
                         ContextMenu = buttonItem22
                     }).ToArray();
                     node.Nodes.AddRange(nodes);
                 }
                 else if (node.Level == 2)
                 {
                     node.Nodes.Clear();
                     Task.Delay(1000);
                     var list = G.GetTablesByDatabase(node.DataKey, node.Text);
                     var nodes = list.Select(a => new Node(a.Name)
                     {
                         Image = Properties.Resources.application,
                        // CheckBoxVisible = true,
                        // CheckBoxStyle = DevComponents.DotNetBar.eCheckBoxStyle.CheckBox,
                        // CheckState = CheckState.Unchecked,
                         Tag = a,
                         DataKey = node.DataKey,
                         ContextMenu = buttonItem23
                     }).ToArray();
                     node.Nodes.AddRange(nodes);
                 }
                 return 0;
             });
            node.Expanded = true;
            this.Invoke((Action)delegate () { Thread.CurrentThread.Join(500); frmLoading.Close(); });
        }

19 Source : LockTests.cs
with MIT License
from 2881099

[Fact]
		public void Lock1()
		{
			var tasks = new Task[4];
			for (var a = 0; a < tasks.Length; a++)
				tasks[a] = Task.Run(() => {
					var lk = cli.Lock("testlock1", 10);
					Thread.CurrentThread.Join(1000);
					replacedert.True(lk.Unlock());
				});
			Task.WaitAll(tasks);
		}

19 Source : DbList.cs
with MIT License
from 2881099

[JSFunction]
        public async Task TestDbconnection(string id)
        {
            await Task.Run(() =>
            {

                if (Guid.TryParse(id, out Guid gid) && gid != Guid.Empty)
                {
                    var enreplacedy = Curd.DataBase.Select.WhereDynamic(gid).ToOne();
                    try
                    {
                        using (var fsql = new FreeSql.FreeSqlBuilder()
                        .UseConnectionString(enreplacedy.DataType, enreplacedy.ConnectionStrings).Build())
                        {
                            Invoke(() =>
                            {
                                InvokeJS("Helper.ui.removeDialog();");
                                InvokeJS($"Helper.ui.dialogSuccess('提示','数据库连接成功');");
                            });
                        }
                    }
                    catch (Exception e)
                    {
                        Invoke(() =>
                        {
                            InvokeJS("Helper.ui.removeDialog();");
                            InvokeJS($"Helper.ui.dialogError('连接失败','{e.Message}');");
                        });
                    }
                }
            });
        }

19 Source : SpeedtestHandler.cs
with GNU General Public License v3.0
from 2dust

private void RunRealPing()
        {
            int pid = -1;
            try
            {
                string msg = string.Empty;

                pid = _v2rayHandler.LoadV2rayConfigString(_config, _selecteds);
                if (pid < 0)
                {
                    _updateFunc(_selecteds[0], UIRes.I18N("OperationFailed"));
                    return;
                }

                //Thread.Sleep(5000);
                int httpPort = _config.GetLocalPort("speedtest");
                List<Task> tasks = new List<Task>();
                foreach (int itemIndex in _selecteds)
                {
                    if (_config.vmess[itemIndex].configType == (int)EConfigType.Custom)
                    {
                        continue;
                    }
                    tasks.Add(Task.Run(() =>
                    {
                        try
                        {
                            WebProxy webProxy = new WebProxy(Global.Loopback, httpPort + itemIndex);
                            int responseTime = -1;
                            string status = GetRealPingTime(_config.speedPingTestUrl, webProxy, out responseTime);
                            string output = Utils.IsNullOrEmpty(status) ? FormatOut(responseTime, "ms") : FormatOut(status, "");
                            _updateFunc(itemIndex, output);
                        }
                        catch (Exception ex)
                        {
                            Utils.SaveLog(ex.Message, ex);
                        }
                    }));
                    //Thread.Sleep(100);
                }
                Task.WaitAll(tasks.ToArray());
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
            }
            finally
            {
                if (pid > 0) _v2rayHandler.V2rayStopPid(pid);
            }
        }

19 Source : SpeedtestHandler.cs
with GNU General Public License v3.0
from 2dust

public int RunAvailabilityCheck() // alias: isLive
        {
            try
            {
                int httpPort = _config.GetLocalPort(Global.InboundHttp);

                Task<int> t = Task.Run(() =>
                {
                    try
                    {
                        WebProxy webProxy = new WebProxy(Global.Loopback, httpPort);
                        int responseTime = -1;
                        string status = GetRealPingTime(Global.AvailabilityTestUrl, webProxy, out responseTime);
                        bool noError = Utils.IsNullOrEmpty(status);
                        return noError ? responseTime : -1;
                    }
                    catch (Exception ex)
                    {
                        Utils.SaveLog(ex.Message, ex);
                        return -1;
                    }
                });
                return t.Result;
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
                return -1;
            }
        }

19 Source : DownloadManager.cs
with MIT License
from 404Lcc

public void DownloadAsync(DownloadData downloadData)
        {
            DownloadFile downloadFile = new DownloadFile(downloadData);
            lock (lockObject)
            {
                readyQueue.Enqueue(downloadFile);
            }
            if (runnings.Count >= taskCount) return;
            Task task = Task.Run(DownloadTask);
            task.Start();
        }

19 Source : DownloadManager.cs
with MIT License
from 404Lcc

public void UpdateTask()
        {
            if (readyQueue.Count == 0 && runnings.Count == 0) return;
            lock (lockObject)
            {
                List<Thread> threadList = new List<Thread>();
                foreach (DictionaryEntry item in runnings)
                {
                    //卡死线程
                    if (!((Thread)item.Key).IsAlive)
                    {
                        if (item.Value != null)
                        {
                            readyQueue.Enqueue((DownloadFile)item.Value);
                        }
                        threadList.Add((Thread)item.Key);
                    }
                }
                foreach (Thread item in threadList)
                {
                    item.Abort();
                    runnings.Remove(item);
                }
            }
            if (NetworkUtil.CheckNetwork())
            {
                if (runnings.Count < taskCount && readyQueue.Count > 0)
                {
                    Task task = Task.Run(DownloadTask);
                    task.Start();
                }
            }
        }

19 Source : WebhookServerBase.cs
with MIT License
from 4egod

private async Task Get(HttpRequest request, HttpResponse response, RouteData route)
        {
            var eventId = new EventId(EventId++);

            try
            {
                if (GetReceived != null)
                {
                    await Task.Run(() =>
                    {
                        GetReceived.Invoke(new WebhookEventArgs()
                        {
                            Request = request,
                            Response = response
                        });
                    });
                }
            }
            catch (Exception e)
            {
                Logger.LogError(eventId, e, e.Message);
            }
        }

19 Source : WebhookServerBase.cs
with MIT License
from 4egod

private async Task Post(HttpRequest request, HttpResponse response, RouteData route)
        {
            var eventId = new EventId(EventId++);
            
            try
            {
                byte[] bodyRaw = new byte[request.ContentLength.Value];
                await request.Body.ReadAsync(bodyRaw, 0, bodyRaw.Length);

                string body = Encoding.UTF8.GetString(bodyRaw);

                if (PostReceived != null)
                {
                    await Task.Run(() =>
                    {
                        PostReceived.Invoke(new WebhookEventArgs()
                        {
                            Request = request,
                            BodyRaw = bodyRaw,
                            Body = body,
                            Response = response
                        });
                    });
                }
            }
            catch (Exception e)
            {
                Logger.LogError(eventId, e, e.Message);
            }
        }

19 Source : MessageDealWidth.cs
with Apache License 2.0
from 51core

public static async Task DealWidth(string message,ChatHub chatHub)
        {
            await Task.Run(() => {
                try
                {
                    MessageData data = JsonConvert.DeserializeObject<MessageData>(message);
                    if (data != null)
                    {
                        ConnectionUser connectionUser = null;
                        MessageData sendMsg = null;
                        switch (data.MessageType)
                        {
                            case MessageType.Line:
                                connectionUser = ConnectionManager.ConnectionUsers.Where(m => m.ConnectionId == chatHub.Context.ConnectionId).FirstOrDefault();
                                //处理连接消息
                                if (connectionUser == null)
                                {
                                    connectionUser = new ConnectionUser();
                                    connectionUser.ConnectionId = chatHub.Context.ConnectionId;
                                    connectionUser.UserId = data.SendUserId;
                                    ConnectionManager.ConnectionUsers.Add(connectionUser);
                                }
                                //处理发送回执消息
                                sendMsg = new MessageData();
                                sendMsg.MessageBody = "";
                                sendMsg.MessageType = MessageType.LineReceipt;
                                sendMsg.SendUserId = "0";
                                chatHub.Clients.Client(chatHub.Context.ConnectionId).SendAsync("receive", JsonConvert.SerializeObject(sendMsg));
                                break;
                            case MessageType.Text:
                                //处理普通文字消息
                                ChatCore.SendMessage(chatHub, data);
                                break;
                            case MessageType.LineReceipt:
                                //处理连接回执消息
                                ChatCore.SendMessage(chatHub, data);
                                break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            });
        }

19 Source : SkillEventHandler.cs
with GNU Lesser General Public License v3.0
from 8720826

public async Task Handle(EnreplacedyDeletedEvent<SkillEnreplacedy> message, CancellationToken cancellationToken)
        {
            var key = string.Format(CacheKey.Skill, message.Enreplacedy.Id);
            await Task.Run(() => {
                _cache.Remove(key);

                _cache.Remove(CacheKey.BaseSkills);
            });
        }

19 Source : ConfigDomainService.cs
with GNU Lesser General Public License v3.0
from 8720826

public async Task<List<ConfigModel>> FormatConfigs(Dictionary<string, string> configDic)
        {
            return await Task.Run(() =>
            {
                return GetAppConfigValue(configDic, typeof(AppConfig));
            });
           
        }

19 Source : RedisConfigurationProvider.cs
with GNU Lesser General Public License v3.0
from 8720826

public async Task LoadData()
        {
            await Task.Run(() =>
            {
                var redis = ConnectionMultiplexer.Connect(_source.RedisString);
                var configurations = redis.GetDatabase().HashGetAll(_source.ConfigKey);

                if (configurations.Length == 0)
                    return;

                var dictionary = configurations.ToDictionary(it => it.Name.ToString(), it => it.Value.ToString());
                Data = new Dictionary<string, string>(dictionary, StringComparer.OrdinalIgnoreCase);
            });
        }

19 Source : SkillEventHandler.cs
with GNU Lesser General Public License v3.0
from 8720826

public async Task Handle(EnreplacedyUpdatedEvent<SkillEnreplacedy> message, CancellationToken cancellationToken)
        {
            var key = string.Format(CacheKey.Skill, message.Enreplacedy.Id);
            await Task.Run(() => {
                _cache.Remove(key);
  
                _cache.Remove(CacheKey.BaseSkills);
            });
        }

19 Source : SkillEventHandler.cs
with GNU Lesser General Public License v3.0
from 8720826

public async Task Handle(EnreplacedyInsertedEvent<SkillEnreplacedy> message, CancellationToken cancellationToken)
        {
            var key = string.Format(CacheKey.Skill, message.Enreplacedy.Id);
            await Task.Run(() => {
                _cache.Set(key, message.Enreplacedy);

                _cache.Remove(CacheKey.BaseSkills);
            });
        }

19 Source : ClientForm1.cs
with MIT License
from a11s

private void button_init_Click(object sender, EventArgs e)
        {
            if (client != null)
            {
                client.Close();
            }
            if (cb_isUdp.Checked)
            {
                client = new k.UdpClient("Test".ToCharArray().Select(a => (byte)a).ToArray(), 0, "udppeer".ToCharArray().Select(a => (byte)a).ToArray());
            }
            else
            {
                if (cb_unreliable.Checked)
                {
                    client = new k.KcpClientEx("Test".ToCharArray().Select(a => (byte)a).ToArray(), 0, "mixpeer".ToCharArray().Select(a => (byte)a).ToArray());
                }
                else
                {
                    client = new k.KcpClient("Test".ToCharArray().Select(a => (byte)a).ToArray(), 0, "kcppeer".ToCharArray().Select(a => (byte)a).ToArray());
                }
            }
            var userid = uint.Parse(textBox_sid.Text);
            var arr = textBox_local.Text.Split(":"[0]);
            localipep = new IPEndPoint(IPAddress.Parse(arr[0]), int.Parse(arr[1]));
            arr = textBox_remote.Text.Split(":"[0]);
            remoteipep = new IPEndPoint(IPAddress.Parse(arr[0]), int.Parse(arr[1]));
            client.OnOperationResponse = (buf) =>
            {
                if (cb_isUdp.Checked)
                {

                    var i = BitConverter.ToInt64(buf, 0);
                    Console.Write($"rec:{i}");
                    Task.Run(() =>
                                {
                                    var snd = i + 1;
                                    Console.WriteLine($"udp snd:{snd}");
                                    client.SendOperationRequest(BitConverter.GetBytes(snd));
                                }
                            );
                }
                else
                {
                    if (cb_unreliable.Checked)//is unreliable
                    {
                        if (buf.Length == sizeof(UInt64))
                        {
                            var i = BitConverter.ToInt64(buf, 0);
                            Console.Write($"rec:{i}");
                            Task.Run(() =>
                            {
                                var snd = i + 1;
                                Console.WriteLine($"unreliable snd:{snd}");
                                clientex?.SendOperationRequest(BitConverter.GetBytes(snd), true);
                            }
                            );
                        }
                        else
                        {
                            //
                            Console.WriteLine($"{nameof(CheckBigBBuff)}={CheckBigBBuff(buf)} size:{buf.Length} reliable");
                        }
                    }
                    else
                    {
                        Console.WriteLine($"{nameof(CheckBigBBuff)}={CheckBigBBuff(buf)} size:{buf.Length} client or clientex.reliable");
                    }
                }
            };
            client.OnConnected = (sid) =>
            {
                this.Invoke(
                    new Action(() =>
                    {
                        this.Text = sid.ToString();
                    })
                    );

            };

            client.Connect(remoteipep, true);
        }

19 Source : ClientUdp.cs
with MIT License
from a11s

private void button_init_Click(object sender, EventArgs e)
        {
            if (client != null)
            {
                client.Close();
            }
            client = new k.UdpClient("Test".ToCharArray().Select(a => (byte)a).ToArray(), 0, "udppeer".ToCharArray().Select(a => (byte)a).ToArray());

            var arr = textBox_remote.Text.Split(":"[0]);
            remoteipep = new IPEndPoint(IPAddress.Parse(arr[0]), int.Parse(arr[1]));
            client.OnOperationResponse = (buf) =>
            {
                var i = BitConverter.ToInt64(buf, 0);
                //Console.Write($"rec:{i}");
                Task.Run(() =>
                {
                    var snd = i + 1;
                    Console.WriteLine($"udp snd:{snd}");
                    client.SendOperationRequest(BitConverter.GetBytes(snd));
                }
                        );
            };
            client.OnConnected = (sid) =>
            {
                this.Invoke(
                    new Action(() =>
                    {
                        this.Text = sid.ToString();
                    })
                    );
            };

            client.Connect(remoteipep, true);
        }

19 Source : RequestFm.cs
with GNU General Public License v3.0
from a4004

private void submit_Click(object sender, EventArgs e)
        {
            if (option1.Checked)
                Option = 1;
            else if (option2.Checked)
                Option = 2;
            else
                Option = 0;

            System.Threading.Tasks.Task.Run(() => WindowManager.UnmountWindow(Parent.Controls, Instance));
        }

19 Source : FileChecker.cs
with Apache License 2.0
from AantCoder

private static void GetCheckSum(ModelFileInfo mfi, string fileName, FastComputeHash computeHash)
        {
            try
            {
                if (computeHash.ReadFile != null) computeHash.ReadFile.Wait();

                computeHash.ReadFile = Task.Run(() =>
                {
                    try
                    {
                        if (!File.Exists(fileName)) return null;
                        var fileData = File.ReadAllBytes(fileName);
                        mfi.Size = fileData.Length;
                        return fileData;
                    }
                    catch (Exception exp)
                    {
                        ExceptionUtil.ExceptionLog(exp, "GetCheckSum 2 " + fileName);
                    }
                    return null;
                });
                computeHash.GetHash = computeHash.ReadFile.ContinueWith((task) =>
                {
                    try
                    {
                        if (task.Result == null)
                        {
                            mfi.Hash = null;
                            return;
                        }
                        var sha = SHA512.Create();
                        mfi.Hash = sha.ComputeHash(task.Result);
                    }
                    catch(Exception exp)
                    {
                        ExceptionUtil.ExceptionLog(exp, "GetCheckSum 3 " + fileName);
                    }
                });

                /*
                var sha = SHA512.Create();
                using (var fs = new FileStream(fileName, FileMode.Open))
                {
                    return sha.ComputeHash(fileData);
                }
                */
            }
            catch(Exception exp)
            {
                ExceptionUtil.ExceptionLog(exp, "GetCheckSum 1 " + fileName);
            }
        }

19 Source : DigitalAnalyzerExampleViewModel.cs
with MIT License
from ABTSoftware

private async Task GenerateData(List<byte[]> digitalChannels, List<float[]> replacedogChannels)
        {
            var digitalChannelsCount = digitalChannels.Count;
            var replacedogChannelsCount = replacedogChannels.Count;

            var totalChannelCount = digitalChannelsCount + replacedogChannelsCount;
            var channelList = new List<ChannelViewModel>(totalChannelCount);
            var channelIndex = ChannelViewModels.Count;

            await Task.Run(async () =>
            {
                var xStart = 0d;
                var xStep = 1d;

                var digital = new List<Task<ChannelViewModel>>(digitalChannelsCount);
                var replacedog = new List<Task<ChannelViewModel>>(replacedogChannelsCount);

                foreach (var channel in digitalChannels)
                {
                    var id = channelIndex++;
                    digital.Add(Task.Run(() => ChannelGenerationHelper.Instance.GenerateDigitalChannel(xStart, xStep, channel, id)));
                }
                foreach (var channel in replacedogChannels)
                {
                    var id = channelIndex++;
                    replacedog.Add(Task.Run(() => ChannelGenerationHelper.Instance.GeneratereplacedogChannel(xStart, xStep, channel, id)));
                }

                await Task.WhenAll(digital.Union(replacedog));

                foreach (var p in digital.Union(replacedog))
                {
                    channelList.Add(p.Result);
                }
            });

            channelList.ForEach(ch => ChannelViewModels.Add(ch));
        }

19 Source : Lidar3DPointCloudDemoView.xaml.cs
with MIT License
from ABTSoftware

public static async Task<XyzDataSeries3D<float>> ParseToXyzDataSeries(global::Lidar3DPointCloudDemo.AscData lidarData, string identifier)
        {
            var xyzDataSeries3D = new XyzDataSeries3D<float> { SeriesName = identifier };

            await Task.Run(() =>
            {
                if (lidarData.ColorValues.IsNullOrEmpty())
                {
                    xyzDataSeries3D.Append(lidarData.XValues, lidarData.YValues, lidarData.ZValues);
                }
                else
                {
                    xyzDataSeries3D.Append(lidarData.XValues, lidarData.YValues, lidarData.ZValues, lidarData.ColorValues.Select(x => new PointMetadata3D(x)));
                }
            });

            return xyzDataSeries3D;
        }

19 Source : App.xaml.cs
with MIT License
from ABTSoftware

private void Application_Startup(object sender, StartupEventArgs e)
        {
            if (e.Args.Contains(_devMode, StringComparer.InvariantCultureIgnoreCase))
            {
                DeveloperModManager.Manage.IsDeveloperMode = true;
            }

            if (e.Args.Contains(_quickStart, StringComparer.InvariantCultureIgnoreCase))
            {
                // Used in automation testing, disable animations and delays in transitions 
                UIAutomationTestMode = true;
                SeriesAnimationBase.GlobalEnableAnimations = false;
            }

            try
            {
                Thread.CurrentThread.Name = "UI Thread";

                Log.Debug("--------------------------------------------------------------");
                Log.DebugFormat("SciChart.Examples.Demo: Session Started {0}",
                    DateTime.Now.ToString("dd MMM yyyy HH:mm:ss"));
                Log.Debug("--------------------------------------------------------------");

                var replacedembliesToSearch = new[]
                {
                    typeof (MainWindowViewModel).replacedembly,
                    typeof (AbtBootstrapper).replacedembly, // SciChart.UI.Bootstrap
                    typeof (IViewModelTrait).replacedembly, // SciChart.UI.Reactive 
                };

                _bootStrapper = new Bootstrapper(ServiceLocator.Container, new AttributedTypeDiscoveryService(new ExplicitreplacedemblyDiscovery(replacedembliesToSearch)));
                _bootStrapper.InitializeAsync().Then(() =>
                {
                    if (!UIAutomationTestMode)
                    {
                        // Do this on background thread
                        Task.Run(() =>
                        {
                            //Syncing usages 
                            var syncHelper = ServiceLocator.Container.Resolve<ISyncUsageHelper>();
                            syncHelper.LoadFromIsolatedStorage();

                            //Try sync with service
                            syncHelper.GetRatingsFromServer();
                            syncHelper.SendUsagesToServer();
                            syncHelper.SetUsageOnExamples();
                        });
                    }

                    _bootStrapper.OnInitComplete();
                }).Catch(ex =>
                {
                    Log.Error("Exception:\n\n{0}", ex);
                    MessageBox.Show("Exception occurred in SciChart.Examples.Demo.\r\n. Please send log files located at %CurrentUser%\\AppData\\Local\\SciChart\\SciChart.Examples.Demo.log to support");
                });
            }
            catch (Exception caught)
            {
                Log.Error("Exception:\n\n{0}", caught);
                MessageBox.Show("Exception occurred in SciChart.Examples.Demo.\r\n. Please send log files located at %CurrentUser%\\AppData\\Local\\SciChart\\SciChart.Examples.Demo.log to support");
            }
        }

19 Source : FifoBillionPointsPageViewModel.cs
with MIT License
from ABTSoftware

private static async Task<List<IRenderableSeriesViewModel>> CreateSeriesAsync(int seriesCount, int pointCount)
        {
            return await Task.Run(() =>
            {
                // Create N series of M points async. Return to calling code to set on the chart 
                IRenderableSeriesViewModel[] series = new IRenderableSeriesViewModel[seriesCount];

                // We generate data in parallel as just generating 1,000,000,000 points takes a long time no matter how fast your chart is! 
                Parallel.For(0, seriesCount, i =>
                {
                    // Temporary buffer for fast filling of DataSeries
                    var xBuffer = new float[AppendCount];
                    var yBuffer = new float[AppendCount];

                    int randomSeed = i * short.MaxValue;
                    var randomWalkGenerator = new Rand(randomSeed);
                    var xyDataSeries = new XyDataSeries<float, float>
                    {
                        // Required for scrolling / streaming 'first in first out' charts
                        FifoCapacity = pointCount,

                        Capacity = pointCount,

                        // Optional to improve performance when you know in advance whether 
                        // data is sorted ascending and contains float.NaN or not 
                        DataDistributionCalculator = new UserDefinedDistributionCalculator<float, float>
                        {
                            ContainsNaN = false,
                            IsEvenlySpaced = true,
                            IsSortedAscending = true,
                        },

                        // Just replacedociate a random walk generator with the series for more consistent random generation
                        Tag = randomWalkGenerator
                    };

                    int yOffset = i + i;
                    for (int j = 0; j < pointCount; j += AppendCount)
                    {
                        for (int k = 0; k < AppendCount; k++)
                        {
                            xBuffer[k] = j + k;
                            yBuffer[k] = randomWalkGenerator.NextWalk() + yOffset;
                        }

                        xyDataSeries.Append(xBuffer, yBuffer);
                    }

                    // Store the series 
                    series[i] = new LineRenderableSeriesViewModel
                    {
                        DataSeries = xyDataSeries,
                        Stroke = GetRandomColor()
                    };
                });

                // Force a GC Collect before we begin
                GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);

                return series.ToList();
            });
        }

19 Source : Lidar3DPointCloudDemoView.xaml.cs
with MIT License
from ABTSoftware

public static async Task<UniformGridDataSeries3D<float>> ParseToGridDataSeries(global::Lidar3DPointCloudDemo.AscData lidarData, string identifier)
        {
            UniformGridDataSeries3D<float> uniformGridDataSeries = null;

            await Task.Run(() =>
            {
                uniformGridDataSeries = new UniformGridDataSeries3D<float>(lidarData.NumberColumns, lidarData.NumberRows) 
                {
                    SeriesName = identifier, 
                    StartX = 0, 
                    StepX = lidarData.CellSize, 
                    StartZ = 0, 
                    StepZ = lidarData.CellSize
                };

                for (int index = 0, z = 0; z < lidarData.NumberRows; z++)
                {
                    for (var x = 0; x < lidarData.NumberColumns; x++)
                    {
                        uniformGridDataSeries.InternalArray[z][x] = lidarData.YValues[index++];
                    }
                }
            });

            return uniformGridDataSeries;
        }

See More Examples