System.Threading.Tasks.Task.Wait()

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

2263 Examples 7

19 Source : Program.cs
with MIT License
from 0x1000000

private static int Run<TOpts>(TOpts opts, Func<TOpts,Task> task)
        {
            try
            {
                task(opts).Wait();
                return 0;
            }
            catch (SqExpressCodeGenException e)
            {
                Console.WriteLine(e.Message);
                return 1;
            }
            catch (AggregateException e) when (e.InnerException is SqExpressCodeGenException sqExpressCodeGenException)
            {
                Console.Error.WriteLine(sqExpressCodeGenException.Message);
                return 1;
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Unhandled Exception: ");
                Console.Error.WriteLine(e);
                return 1;
            }
        }

19 Source : RedisSocket.cs
with MIT License
from 2881099

public Stream GetStream()
        {
            Stream netStream = new NetworkStream(_socket, true);

            if (!_ssl) return netStream;

            var sslStream = new SslStream(netStream, true);
#if net40
            sslStream.AuthenticateAsClient(GetHostForAuthentication());
#else
            sslStream.AuthenticateAsClientAsync(GetHostForAuthentication()).Wait();
#endif
            return sslStream;
        }

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 : 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 : SagaMaster.cs
with MIT License
from 2881099

internal static Action GetTempTask(FreeSqlCloud<TDBKey> cloud, string tid, string replacedle, int retryInterval)
        {
            return () =>
            {
                try
                {
#if net40
                    Cancel(cloud, tid, true);
#else
                    CancelAsync(cloud, tid, true).Wait();
#endif
                }
                catch
                {
                    try
                    {
                        cloud._ormMaster.Update<SagaMasterInfo>()
                            .Where(a => a.Tid == tid && a.Status == SagaMasterStatus.Pending)
                            .Set(a => a.RetryCount + 1)
                            .Set(a => a.RetryTime == DateTime.UtcNow)
                            .ExecuteAffrows();
                    }
                    catch { }
                    //if (cloud._distributeTraceEnable) cloud._distributedTraceCall($"SAGA({tid}, {replacedle}) Not completed, waiting to try again, current tasks {cloud._scheduler.QuanreplacedyTempTask}");
                    cloud._scheduler.AddTempTask(TimeSpan.FromSeconds(retryInterval), GetTempTask(cloud, tid, replacedle, retryInterval));
                }
            };
        }

19 Source : TccMaster.cs
with MIT License
from 2881099

internal static Action GetTempTask(FreeSqlCloud<TDBKey> cloud, string tid, string replacedle, int retryInterval)
        {
            return () =>
            {
                try
                {
#if net40
                    ConfimCancel(cloud, tid, true);
#else
                    ConfimCancelAsync(cloud, tid, true).Wait();
#endif
                }
                catch
                {
                    try
                    {
                        cloud._ormMaster.Update<TccMasterInfo>()
                            .Where(a => a.Tid == tid && a.Status == TccMasterStatus.Pending)
                            .Set(a => a.RetryCount + 1)
                            .Set(a => a.RetryTime == DateTime.UtcNow)
                            .ExecuteAffrows();
                    }
                    catch { }
                    //if (cloud.TccTraceEnable) cloud.OnTccTrace($"TCC ({tid}, {replacedle}) Not completed, waiting to try again, current tasks {cloud._scheduler.QuanreplacedyTempTask}");
                    cloud._scheduler.AddTempTask(TimeSpan.FromSeconds(retryInterval), GetTempTask(cloud, tid, replacedle, retryInterval));
                }
            };
        }

19 Source : DebugProgramTemplate.cs
with MIT License
from 71

public static int Main(string[] args)
    {
        try
        {
            Diagnosticreplacedyzer replacedyzer = new Cometaryreplacedyzer();
            CSharpParseOptions parseOptions = new CSharpParseOptions(preprocessorSymbols: new[] { "DEBUGGING" });

            if (IsWrittenToDisk && ShouldBreakAtStart)
                Debugger.Break();

            CompilationWithreplacedyzers compilation = CSharpCompilation.Create(
                replacedemblyName + "+Debugging",
                Files.Split(';').Select(x => CSharpSyntaxTree.ParseText(File.ReadAllText(x), parseOptions)),
                References.Split(';').Select(x => MetadataReference.CreateFromFile(x))
            ).Withreplacedyzers(ImmutableArray.Create(replacedyzer));

            ExecuteAsync(compilation).Wait();

            return 0;
        }
        catch (Exception e)
        {
            Console.Error.WriteLine(e.Message);
            Console.Error.WriteLine();
            Console.Error.WriteLine(e.StackTrace);

            Console.ReadKey();

            return 1;
        }
    }

19 Source : TestUnlimitedBuffer.cs
with MIT License
from a1q123456

[TestMethod]
        public void TestAsyncWriteAndRead()
        {
            var buffer = new ByteBuffer(512, 35767);
            short c = 0;
            Func<Task> th1 = async () =>
            {
                byte i = 0;
                while (c < short.MaxValue)
                {
                    var arr = new byte[new Random().Next(256, 512)];
                    for (var j = 0; j < arr.Length; j++)
                    {
                        arr[j] = i;
                        i++;

                        if (i > 100)
                        {
                            i = 0;
                        }
                    }
                    await buffer.WriteToBufferAsync(arr);
                    c++;
                }
            };

            Func<Task> th2 = async () =>
            {
                while (c < short.MaxValue)
                {
                    var arr = new byte[new Random().Next(129, 136)];
                    if (buffer.Length >= arr.Length)
                    {
                        await buffer.TakeOutMemoryAsync(arr);

                        for (int i = 1; i < arr.Length; i++)
                        {
                            replacedert.IsTrue(arr[i] - arr[i - 1] == 1 || arr[i - 1] - arr[i] == 100);
                        }
                    }
                }
            };

            var t = th1();
            th2();
            t.Wait();
        }

19 Source : BitfinexTest.cs
with MIT License
from aabiryukov

public static void Test()
		{

            using (var wsApi = new BitfinexSocketApi())
			{
                BitfinexSocketApi.SetLogVerbosity(Bitfinex.Logging.LogVerbosity.Info);

                Console.WriteLine("Bitfinex: Socket starting...");
                wsApi.Connect();

                Task.Delay(3000).Wait();
/*
                var subcribtion1 = wsApi.SubscribeToTradingPairTicker("tETHBTC", summary =>
                {
                    Console.WriteLine($"{DateTime.Now} BTC-ETH: {summary.LastPrice}");
                });
                Console.WriteLine($"Subcribtion1: {subcribtion1}");
*/

                var subcribtion2 = wsApi.SubscribeToOrderBooks("tETHBTC", OnOrderBooks, frequency: Frequency.F0, length: 1);
                Console.WriteLine($"Subcribtion2: {subcribtion2}");

                Console.ReadLine();
			}

/*
			var ticker = BitfinexApi.GetPublicTicker(BtcInfo.PairTypeEnum.btcusd, BtcInfo.BitfinexUnauthenicatedCallsEnum.pubticker);
			Console.WriteLine(ticker.LastPrice);

			var trades = BitfinexApi.GetPairTrades(BtcInfo.PairTypeEnum.btcusd, BtcInfo.BitfinexUnauthenicatedCallsEnum.trades);
			Console.WriteLine("trades.Count=" + trades.Count);

			var orderBook = BitfinexApi.GetOrderBook(BtcInfo.PairTypeEnum.btcusd);
			Console.WriteLine("orderBook.Asks.Length={0}, orderBook.Bids.Length={1}", orderBook.Asks.Length, orderBook.Bids.Length);
*/
			var api = new BitfinexApi(ApiKey, ApiSecret);

			var balances = api.GetBalances();
			var usd = balances.FirstOrDefault(x => x.Type == "exchange" && x.Currency == "usd");
			var btc = balances.FirstOrDefault(x => x.Type == "exchange" && x.Currency == "btc");
			Console.WriteLine("usd: " + usd);
			Console.WriteLine("btc: " + btc);

			foreach (var balance in balances)
			{
				Console.WriteLine("balance: " + balance);
			}

			var info = api.GetAccountInformation();
			Console.WriteLine("Account info: {0}", info);

			var openOrders = api.GetActiveOrders();
			Console.WriteLine("Open orders: {0}", openOrders.Count());
/*
			var cancelResult = api.CancelOrder(12345);
			Console.WriteLine("CancelOrder: {0}", cancelResult);

			var sellAnswer = api.Sell(12456.3M, 2);
			Console.WriteLine("Sell: {0}", sellAnswer);

			var buyAnswer = api.Buy(12.3M, 1);
			Console.WriteLine("Buy: {0}", buyAnswer);
 */ 
		}

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

public void Wait()
            {
                if (GetHash != null) GetHash.Wait();
            }

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 : SerializedShardDatabase.cs
with GNU Affero General Public License v3.0
from ACEmulator

private void DoWork()
        {
            while (!_queue.IsAddingCompleted)
            {
                try
                {
                    Task t = _queue.Take();

                    try
                    {
                        t.Start();
                        t.Wait();
                    }
                    catch (Exception ex)
                    {
                        log.Error($"[DATABASE] DoWork task failed with exception: {ex}");
                        // perhaps add failure callbacks?
                        // swallow for now.  can't block other db work because 1 fails.
                    }
                }
                catch (ObjectDisposedException)
                {
                    // the _queue has been disposed, we're good
                    break;
                }
                catch (InvalidOperationException)
                {
                    // _queue is empty and CompleteForAdding has been called -- we're done here
                    break;
                }
            }
        }

19 Source : ProcessInvoker.cs
with MIT License
from actions

public void Set()
            {
                var tcs = m_tcs;
                Task.Factory.StartNew(s => ((TaskCompletionSource<bool>)s).TrySetResult(true),
                    tcs, CancellationToken.None, TaskCreationOptions.PreferFairness, TaskScheduler.Default);
                tcs.Task.Wait();
            }

19 Source : VssFileStorage.cs
with MIT License
from actions

private void SaveFile(string path, string content)
            {
                bool success = false;
                int tries = 0;
                int retryDelayMilliseconds = 10;
                const int maxNumberOfRetries = 6;
                do
                {
                    try
                    {
                        using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Delete))
                        {
                            using (var sw = new StreamWriter(fs, Encoding.UTF8))
                            {
                                sw.Write(content);
                            }
                        }
                        success = true;
                    }
                    catch (IOException)
                    {
                        if (++tries > maxNumberOfRetries)
                        {
                            throw;
                        }
                        Task.Delay(retryDelayMilliseconds).Wait();
                        retryDelayMilliseconds *= 2;
                    }
                }
                while (!success);
            }

19 Source : HIVEConnection.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public DbDataReader LoadData()
        {
            DbDataReader dr;
            using (OdbcConnection conn =
             new OdbcConnection("DSN=Hive;UID=user-name;PWD=preplacedword"))//Example
            {
                conn.OpenAsync().Wait();
                OdbcCommand cmd = conn.CreateCommand();
                cmd.CommandText =
                    "SELECT obs_date, avg(temp) FROM weather GROUP BY obs_date;";//Example
                dr = cmd.ExecuteReader();
                while (dr.Read())
                {

                }
                conn.Close();
            }
            return dr;
        }

19 Source : DiagnosticVerifier.cs
with GNU General Public License v3.0
from Acumatica

protected void VerifyCSharpDiagnostic(string source, params DiagnosticResult[] expected) =>
			VerifyDiagnosticsAsync(new[] { source }, LanguageNames.CSharp, 
									GetCSharpDiagnosticreplacedyzer(), expected, checkOnlyFirstDoreplacedent: true).Wait();

19 Source : DiagnosticVerifier.cs
with GNU General Public License v3.0
from Acumatica

protected void VerifyCSharpDiagnostic(string source, bool checkOnlyFirstDoreplacedent, params DiagnosticResult[] expected) =>
			VerifyDiagnosticsAsync(new[] { source }, LanguageNames.CSharp, GetCSharpDiagnosticreplacedyzer(), expected, checkOnlyFirstDoreplacedent).Wait();

19 Source : CodeFixVerifier.cs
with GNU General Public License v3.0
from Acumatica

protected void VerifyCSharpFix(string oldSource, string newSource, int codeFixIndex = 0, bool allowNewCompilerDiagnostics = false)
		{
			VerifyFixAsync(LanguageNames.CSharp, GetCSharpDiagnosticreplacedyzer(), GetCSharpCodeFixProvider(), oldSource, newSource,
							allowNewCompilerDiagnostics, codeFixIndex).Wait();
		}

19 Source : DiagnosticVerifier.cs
with GNU General Public License v3.0
from Acumatica

protected void VerifyCSharpDiagnostic(string[] sources, params DiagnosticResult[] expected) =>
			VerifyDiagnosticsAsync(sources, LanguageNames.CSharp, GetCSharpDiagnosticreplacedyzer(), expected, checkOnlyFirstDoreplacedent: true).Wait();

19 Source : DiagnosticVerifier.cs
with GNU General Public License v3.0
from Acumatica

protected void VerifyCSharpDiagnostic(string[] sources, bool checkOnlyFirstDoreplacedent, params DiagnosticResult[] expected) => 
			VerifyDiagnosticsAsync(sources, LanguageNames.CSharp, GetCSharpDiagnosticreplacedyzer(), expected, checkOnlyFirstDoreplacedent).Wait();

19 Source : PXRoslynColorizerTagger.cs
with GNU General Public License v3.0
from Acumatica

protected internal override IEnumerable<ITagSpan<IClreplacedificationTag>> GetTagsSynchronousImplementation(ITextSnapshot snapshot)
        {
            _clreplacedificationTagsCache.SetCancellation(CancellationToken.None);
            _outliningTagsCache.SetCancellation(CancellationToken.None);

            Task<ParsedDoreplacedent> getDoreplacedentTask = ParsedDoreplacedent.ResolveAsync(Snapshot, CancellationToken.None);

            if (getDoreplacedentTask == null)    // Razor cshtml returns a null doreplacedent for some reason.        
                return ClreplacedificationTagsCache.ProcessedTags; 

            try
            {
				//This method is deliberately synchronous so we ignore warnings
#pragma warning disable VSTHRD002 // Avoid problematic synchronous waits
				getDoreplacedentTask.Wait();

			}
            catch (Exception)
            {
                return ClreplacedificationTagsCache.ProcessedTags;     // TODO: report this to someone.
            }

            ParsedDoreplacedent doreplacedent = getDoreplacedentTask.Result;
#pragma warning restore VSTHRD002 // Avoid problematic synchronous waits

			WalkDoreplacedentSyntaxTreeForTags(doreplacedent, CancellationToken.None);
            //doreplacedentCache = doreplacedent;
            //isParsed = true;
          
            return ClreplacedificationTagsCache.ProcessedTags;
        }

19 Source : RestartApp.cs
with MIT License
from ADefWebserver

[HttpGet("[action]")]
        public ContentResult ShutdownSite()
        {
            string WebConfigOrginalFileNameAndPath = _hostEnvironment.ContentRootPath + @"\Web.config";
            string WebConfigTempFileNameAndPath = _hostEnvironment.ContentRootPath + @"\Web.config.txt";

            if (System.IO.File.Exists(WebConfigOrginalFileNameAndPath))
            {
                // Temporarily rename the web.config file
                // to release the locks on any replacedemblies
                System.IO.File.Copy(WebConfigOrginalFileNameAndPath, WebConfigTempFileNameAndPath);
                System.IO.File.Delete(WebConfigOrginalFileNameAndPath);

                // Give the site time to release locks on the replacedemblies
                Task.Delay(2000).Wait(); // Wait 2 seconds with blocking

                // Rename the temp web.config file back to web.config
                // so the site will be active again
                System.IO.File.Copy(WebConfigTempFileNameAndPath, WebConfigOrginalFileNameAndPath);
                System.IO.File.Delete(WebConfigTempFileNameAndPath);
            }

            return new ContentResult
            {
                ContentType = @"text/html",
                StatusCode = (int)HttpStatusCode.OK,
                Content = $@"<html><body><h2><a href={GetBaseUrl()}>click here to continue</a></h2></body></html>"
            };
        }

19 Source : UploadController.cs
with MIT License
from ADefWebserver

[HttpPost("[action]")]
        public async Task<IActionResult> UpgradeAsync(
            IFormFile file, string Filereplacedle)
        {
            try
            {
                if (HttpContext.Request.Form.Files.Any())
                {
                    // Only accept .zip files
                    if (file.ContentType == "application/x-zip-compressed")
                    {
                        string UploadPath =
                            Path.Combine(
                                environment.ContentRootPath,
                                "Uploads");

                        string UploadPathAndFile =
                            Path.Combine(
                                environment.ContentRootPath,
                                "Uploads",
                                "BlazorBlogsUpgrade.zip");

                        string UpgradePath = Path.Combine(
                            environment.ContentRootPath,
                            "Upgrade");

                        // Upload Upgrade package to Upload Folder
                        if (!Directory.Exists(UpgradePath))
                        {
                            Directory.CreateDirectory(UpgradePath);
                        }

                        using (var stream =
                            new FileStream(UploadPathAndFile, FileMode.Create))
                        {
                            await file.CopyToAsync(stream);
                        }

                        DeleteFiles(UpgradePath);

                        // Unzip files to Upgrade folder
                        ZipFile.ExtractToDirectory(UploadPathAndFile, UpgradePath, true);

                        #region Check upgrade - Get current version
                        Version objVersion = new Version();
                        var GeneralSettings = await generalSettingsService.GetGeneralSettingsAsync();
                        objVersion.VersionNumber = GeneralSettings.VersionNumber;
                        #endregion

                        #region Examine the manifest file
                        objVersion = ReadManifest(objVersion, UpgradePath);

                        try
                        {
                            if (objVersion.ManifestLowestVersion == "")
                            {
                                // Delete the files
                                DeleteFiles(UpgradePath);
                                return Ok("Error: could not find manifest");
                            }
                        }
                        catch (Exception ex)
                        {
                            return Ok(ex.ToString());
                        }
                        #endregion

                        #region Show error if needed and delete upgrade files 
                        if
                            (
                            (ConvertToInteger(objVersion.VersionNumber) > ConvertToInteger(objVersion.ManifestHighestVersion)) ||
                            (ConvertToInteger(objVersion.VersionNumber) < ConvertToInteger(objVersion.ManifestLowestVersion))
                            )
                        {
                            // Delete the files
                            DeleteFiles(UpgradePath);

                            // Return the error response
                            return Ok(objVersion.ManifestFailure);
                        }
                        #endregion

                        // Proceed with upgrade...

                        DeleteFiles(UpgradePath);

                        // Unzip files to final paths
                        ZipFile.ExtractToDirectory(UploadPathAndFile, environment.ContentRootPath, true);

                        Task.Delay(4000).Wait(); // Wait 4 seconds with blocking
                    }
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message);
            }

            return Ok();
        }

19 Source : Program.cs
with MIT License
from adospace

static int Main(string[] args)
        {
            //C:\Program Files (x86)\Android\android-sdk>adb forward tcp:45820 tcp:45821
            if (!ExecutePortForwardCommmand())
                return -1;

            Parser.Default.ParseArguments<Options>(args)
                   .WithParsed(o =>
                   {
                       _remoteServerPort = o.Port;

                       SendreplacedemblyToEmulatorAsync(o.replacedemblyPath).Wait();

                       if (o.Monitor)
                       {
                           Monitor(o.replacedemblyPath);
                       }
                       else
                       { 
                       }
                   });

            return 0;
        }

19 Source : RegistrationManager.cs
with MIT License
from Adoxio

public string FindEmailByInvitationCode(string invitationCode)
		{
			if (Adxstudio.Xrm.Configuration.PortalSettings.Instance.Ess.IsEss || !this.Settings.RegistrationEnabled
				|| (!this.Settings.OpenRegistrationEnabled && !this.Settings.InvitationEnabled)
				|| (this.Settings.OpenRegistrationEnabled && !this.Settings.InvitationEnabled && !string.IsNullOrWhiteSpace(invitationCode))
				|| (!this.Settings.OpenRegistrationEnabled && this.Settings.InvitationEnabled && string.IsNullOrWhiteSpace(invitationCode)))
			{
				this.loginManager.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
				this.loginManager.HttpContext.Response.ContentType = "text/plain";
				this.loginManager.HttpContext.Response.Write(ResourceManager.GetString("Not_Found_Exception"));
				this.loginManager.HttpContext.Response.End();
			}
			Task<ApplicationInvitation> invitation = this.loginManager.FindInvitationByCodeAsync(invitationCode);
			invitation.Wait();
			var contactId = this.loginManager.ToContactId(invitation.Result);
			var email = contactId != null ? contactId.Name : null;

			return email;
		}

19 Source : RetryInterceptorTest.cs
with MIT License
from AElfProject

[Fact]
        public async Task Retry_Timeout_Test()
        {
            var helper = new MockServiceBuilder("localhost");
            int callCount = 0;
            helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) =>
            {
                callCount++;

                Task.Delay(1000).Wait();
                
                return Task.FromResult("ok");
            });

            _server = helper.GetServer();
            _server.Start();
            _channel = helper.GetChannel();
            
            var callInvoker = helper.GetChannel().Intercept(new RetryInterceptor());
            
            var metadata = new Metadata {{ GrpcConstants.RetryCountMetadataKey, "1"}};

            var exception = await replacedert.ThrowsAsync<AggregateException>(async () => await callInvoker.AsyncUnaryCall(
                new Method<string, string>(MethodType.Unary,
                    MockServiceBuilder.ServiceName, "Unary", Marshallers.StringMarshaller,
                    Marshallers.StringMarshaller),
                "localhost", new CallOptions().WithHeaders(metadata), ""));

            var rpcException = exception.InnerExceptions[0] as RpcException;
            rpcException.ShouldNotBeNull();
            rpcException.StatusCode.ShouldBe(StatusCode.DeadlineExceeded);

            replacedert.Equal(2, callCount);
        }

19 Source : RedisSocket.cs
with Mozilla Public License 2.0
from agebullhu

public Stream GetStream()
        {
            Stream netStream = new NetworkStream(_socket);

            if (!_ssl) return netStream;

            var sslStream = new SslStream(netStream, true);
			sslStream.AuthenticateAsClientAsync(GetHostForAuthentication()).Wait();
            return sslStream;
        }

19 Source : ZeroApplication.cs
with Mozilla Public License 2.0
from agebullhu

public static void RunAwaite()
        {
            Console.CancelKeyPress += OnCancelKeyPress;
            Console.WriteLine("Zeronet application start...");
            Start();
            Task.Factory.StartNew(WaitTask).Wait();
        }

19 Source : DlnaDeviceHostedService.cs
with MIT License
from aguang-xyz

private ISsdpClient BuildSsdpClient()
        {
            var client = new SsdpClient("urn:schemas-upnp-org:device:MediaRenderer:1");

            client.ServiceAvailable += (sender, info) =>
            {
                RegisterDeviceAsync(info).Wait();
            };

            client.ServiceUnavailable += (sender, info) =>
            {
                UnregisterDevice(info);
            };

            return client;
        }

19 Source : DlnaDeviceAccessor.cs
with MIT License
from aguang-xyz

private void Sync(object sender, ElapsedEventArgs e)
        {
            SyncTask().Wait();
        }

19 Source : TestExtends.cs
with MIT License
from AiursoftWeb

public static void replacedert<T>(this Repository<T> repo, params T[] array)
        {
            repo.WaitTill(array.Length, 9).Wait();
            var commits = repo.Commits.ToArray();
            for (int i = 0; i < commits.Length; i++)
            {
                if (!commits[i].Item.Equals(array[i]))
                {
                    Microsoft.VisualStudio.TestTools.UnitTesting.replacedert.Fail($"The repo don't match! Expected: {string.Join(',', array.Select(t => t.ToString()))}; Actual: {string.Join(',', repo.Commits.Select(t => t.ToString()))}");
                }
            }
        }

19 Source : BasicTests.cs
with MIT License
from AiursoftWeb

public static void replacedertEqual<T>(this Repository<T> repo, Repository<T> repo2, int expectedCount)
        {
            repo.WaitTill(expectedCount, 9).Wait();
            repo2.WaitTill(expectedCount, 9).Wait();
            var commits = repo.Commits.ToArray();
            var commits2 = repo2.Commits.ToArray();
            if (commits.Length != commits2.Length || commits.Length != expectedCount)
            {
                Microsoft.VisualStudio.TestTools.UnitTesting.replacedert.Fail($"The repo  don't match! Expected: {string.Join(',', commits2.Select(t => t.ToString()))}; Actual: {string.Join(',', repo.Commits.Select(t => t.ToString()))}");
            }
            for (int i = 0; i < commits.Length; i++)
            {
                if (!commits[i].Id.Equals(commits2[i].Id))
                {
                    Microsoft.VisualStudio.TestTools.UnitTesting.replacedert.Fail($"The repo don't match! Expected: {string.Join(',', commits2.Select(t => t.ToString()))}; Actual: {string.Join(',', repo.Commits.Select(t => t.ToString()))}");
                }
            }
        }

19 Source : updateForm.cs
with MIT License
from ajohns6

private void checkUpdate(object sender, EventArgs e)
        {
            if (!progressForm.IsConnectedToInternet())
            {
                this.Dispose();
                return;
            }

            string url = "https://api.github.com/repos/ajohns6/SM64-NX-Launcher/releases";
            string releaseString = "";

            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Accept = "application/json";
            request.Method = "GET";
            request.UserAgent = "Foo";
            try
            {
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    releaseString = reader.ReadToEnd();
                }
            }
            catch
            {
                this.Dispose();
                return;
            }

            Application.DoEvents();

            var releaseList = JsonConvert.DeserializeObject<List<release>>(releaseString);

            if (releaseList[0].tag_name != ("v" + version))
            {
                this.statusLabel.Text = "Downloading " + releaseList[0].tag_name + "...";
                this.progBar.Visible = true;
                string tempPath = Path.Combine(Path.GetTempPath(),
                             "sm64nxlauncherinstaller",
                             version);
                string zipPath = Path.Combine(tempPath, "installer.zip");
                mainForm.DeleteDirectory(tempPath);

                Task.Run(() =>
                {
                    using (var client = new WebClient())
                    {
                        if (!Directory.Exists(tempPath))
                        {
                            Directory.CreateDirectory(tempPath);
                        }

                        client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloadProgress);
                        client.DownloadFileCompleted += new AsyncCompletedEventHandler(downloadComplete);
                        Uri installerLink = new Uri(releaseList[0].replacedets[0].browser_download_url);
                        client.DownloadFileAsync(installerLink, zipPath);
                    }
                });

                progBar.Maximum = 100;

                Application.DoEvents();

                do
                {
                    progBar.Value = progress;
                } while (progress < 100);

                do
                {
                    Application.DoEvents();
                } while (!complete);

                this.statusLabel.Text = "Extracting installer...";

                Task.Run(() =>
                {
                    bool unzipped = false;
                    do
                    {
                        try
                        {
                            ZipFile.ExtractToDirectory(zipPath, tempPath);
                            unzipped = true;
                        }
                        catch { }
                    } while (!unzipped);
                }).Wait();

                ProcessStartInfo installStart = new ProcessStartInfo();
                installStart.FileName = Path.Combine(tempPath, "setup.exe");

                Process installer = new Process();
                installer.StartInfo = installStart;

                installer.Start();

                Application.Exit();
            }

            this.Close();
        }

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

public IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
        {
            Task.Delay(dueTime).Wait();
            return action(this, state);
        }

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

public IDisposable Schedule<TState>(TState state, DateTimeOffset dueTime, Func<IScheduler, TState, IDisposable> action)
        {
            var diff = dueTime - Now;
            Task.Delay(diff).Wait();
            return action(this, state);
        }

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

[Test]
        public void Task_TResult_Dispose()
        {
            var cdl = new CountdownEvent(1);

            var task = Task.Factory.StartNew(() =>
            {
                cdl.Wait();
                return 0;
            });

            var co = task.ToCompletable();

            var to = co.Test(true);

            cdl.Signal();

            task.Wait();

            to.replacedertEmpty();
        }

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

[Test]
        public void Task_TResult_Dispose()
        {
            var cdl = new CountdownEvent(1);

            var task = Task.Factory.StartNew(() =>
            {
                cdl.Wait();
                return 0;
            });

            var co = task.ToMaybe();

            var to = co.Test(true);

            cdl.Signal();

            task.Wait();

            to.replacedertEmpty();
        }

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

[Test]
        public void Task_TResult_Dispose()
        {
            var cdl = new CountdownEvent(1);

            var task = Task.Factory.StartNew(() =>
            {
                cdl.Wait();
                return 0;
            });

            var co = task.ToSingle();

            var to = co.Test(true);

            cdl.Signal();

            task.Wait();

            to.replacedertEmpty();
        }

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

[Test]
        public void Task_Dispose()
        {
            var cdl = new CountdownEvent(1);

            var task = Task.Factory.StartNew(() =>
            {
                cdl.Wait();
            });

            var co = task.ToCompletable();

            var to = co.Test(true);

            cdl.Signal();

            task.Wait();

            to.replacedertEmpty();
        }

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

[Test]
        public void Task_Dispose()
        {
            var cdl = new CountdownEvent(1);

            var task = Task.Factory.StartNew(() =>
            {
                cdl.Wait();
            });

            var co = task.ToMaybe<int>();

            var to = co.Test(true);

            cdl.Signal();

            task.Wait();

            to.replacedertEmpty();
        }

19 Source : RenderTests.cs
with MIT License
from Akinzekeel

[TestMethod]
        public void Query_Triggers_Rerender()
        {
            ProviderDelegate<MyDto> provider = (r, _) =>
            {
                return ValueTask.FromResult(new BlazorGridResult<MyDto>
                {
                    TotalCount = 1,
                    Data = new List<MyDto> {
                        new MyDto { Name = "Unit test" }
                    }
                });
            };

            var grid = RenderComponent<BlazorGrid<MyDto>>(
                Parameter(nameof(BlazorGrid<MyDto>.Provider), provider),
                Template<MyDto>(nameof(ChildContent), (context) => (RenderTreeBuilder b) =>
                {
                    Expression<Func<string>> colFor = () => context.Name;

                    b.OpenComponent<GridCol<string>>(0);
                    b.AddAttribute(1, "For", colFor);
                    b.CloseComponent();
                })
            );

            // Now let's try changing the sorting
            var col = grid.FindComponent<GridCol<string>>();
            grid.SetParametersAndRender(
                Parameter(nameof(BlazorGrid<MyDto>.QueryUserInput), "Hello world")
            );

            // Since this property uses a debounce, there shouldn't be any render yet
            replacedert.AreEqual(1, grid.RenderCount);

            // Wait for it...
            Task.Delay(500).Wait();

            replacedert.AreNotEqual(1, grid.RenderCount);
        }

19 Source : RenderTests.cs
with MIT License
from Akinzekeel

[TestMethod]
        public async Task OnClick_Does_Not_Trigger_Rerender()
        {
            ProviderDelegate<MyDto> provider = (r, _) =>
            {
                return ValueTask.FromResult(new BlazorGridResult<MyDto>
                {
                    TotalCount = 1,
                    Data = new List<MyDto> {
                        new MyDto { Name = "Unit test" }
                    }
                });
            };

            var clickCount = 0;
            var grid = RenderComponent<BlazorGrid<MyDto>>(
                Parameter(nameof(BlazorGrid<MyDto>.Provider), provider),
                EventCallback<MyDto>(nameof(BlazorGrid<MyDto>.OnClick), _ => clickCount++),
                Template<MyDto>(nameof(ChildContent), (context) => (RenderTreeBuilder b) =>
                {
                    Expression<Func<string>> colFor = () => context.Name;

                    b.OpenComponent<GridCol<string>>(0);
                    b.AddAttribute(1, "For", colFor);
                    b.CloseComponent();
                })
            );

            // Try clicking on a row
            var row = grid.Find(".grid-row:not(.grid-header)");
            await grid.InvokeAsync(() => row.Click());

            Task.Delay(100).Wait();

            replacedert.AreEqual(1, grid.RenderCount);
        }

19 Source : RenderTests.cs
with MIT License
from Akinzekeel

[TestMethod]
        public async Task OnClick_With_Highlighting_Adds_Row_Clreplaced()
        {
            ProviderDelegate<MyDto> provider = (r, _) =>
            {
                return ValueTask.FromResult(new BlazorGridResult<MyDto>
                {
                    TotalCount = 1,
                    Data = new List<MyDto> {
                        new MyDto { Name = "Unit test" }
                    }
                });
            };

            int clickCount = 0;
            var grid = RenderComponent<BlazorGrid<MyDto>>(
                Parameter(nameof(BlazorGrid<MyDto>.Provider), provider),
                Parameter(nameof(BlazorGrid<MyDto>.RowHighlighting), true),
                EventCallback<MyDto>(nameof(BlazorGrid<MyDto>.OnClick), _ => clickCount++),
                Template<MyDto>(nameof(ChildContent), (context) => (RenderTreeBuilder b) =>
                {
                    Expression<Func<string>> colFor = () => context.Name;

                    b.OpenComponent<GridCol<string>>(0);
                    b.AddAttribute(1, "For", colFor);
                    b.CloseComponent();
                })
            );

            // Try clicking on a row
            var row = grid.Find(".grid-row:not(.grid-header)");
            await grid.InvokeAsync(() => row.Click());

            Task.Delay(100).Wait();

            row = grid.Find(".grid-row:not(.grid-header)");
            replacedert.IsTrue(row.Matches(".highlighted"), row.ToMarkup());
        }

19 Source : DatabaseFixture.cs
with Apache License 2.0
from AkkaNetContrib

public DatabaseFixture Restart()
        {
            if (_restartCount++ == 0) return this; // Don't restart the first time
            _client.Containers.RestartContainerAsync(_eventStoreContainerName, new ContainerRestartParameters { WaitBeforeKillSeconds = 0 }).Wait();
            Task.Delay(5000).Wait();
            InitializeProjections(_httpPort).Wait();
            return this;
        }

19 Source : Comment.cs
with MIT License
from AlaricGilbert

public static async Task<string> SendAsync(string av_number, string comment)
        {
            var req = WebRequest.CreateHttp($"https://api.bilibili.com/x/v2/reply/add?oid={av_number}&type=1&message={comment}&plat=1&jsonp=jsonp&csrf={Account.CookieJObjet["bili_jct"].Value<string>()}");
            req.Method = "POST";
            req.Host = "api.bilibili.com";
            //req.Connection = "keep-alive";
            req.Accept = "application/json, text/javascript, */*; q=0.01";
            req.UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36";
            req.ContentType = "application/x-www-form-urlencoded";
            req.Referer = "https://www.bilibili.com/video/av" + av_number;
            req.Headers.Add("Accept-Encoding", "gzip, deflate, br");
            req.Headers.Add("Accept-Language", "zh-CN,zh;q=0.9");
            req.Headers.Add("Cookie", Account.CookieString);
            var response = await req.GetResponseAsync();
            var r_stream = response.GetResponseStream();
            byte[] buffer = new byte[response.ContentLength];
            r_stream.ReadAsync(buffer, 0, (int)response.ContentLength).Wait();
            return Encoding.UTF8.GetString(buffer);
        }

19 Source : AppHost.cs
with MIT License
from alethic

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

19 Source : DnsSecRecursiveDnsResolver.cs
with Apache License 2.0
from alexreinert

public List<T> Resolve<T>(DomainName name, RecordType recordType = RecordType.A, RecordClreplaced recordClreplaced = RecordClreplaced.INet)
			where T : DnsRecordBase
		{
			var res = ResolveAsync<T>(name, recordType, recordClreplaced);
			res.Wait();
			return res.Result;
		}

19 Source : DnsSecRecursiveDnsResolver.cs
with Apache License 2.0
from alexreinert

public DnsSecResult<T> ResolveSecure<T>(DomainName name, RecordType recordType = RecordType.A, RecordClreplaced recordClreplaced = RecordClreplaced.INet)
			where T : DnsRecordBase
		{
			var res = ResolveSecureAsync<T>(name, recordType, recordClreplaced);
			res.Wait();
			return res.Result;
		}

19 Source : DnsClientBase.cs
with Apache License 2.0
from alexreinert

protected List<TMessage> SendMessageParallel<TMessage>(TMessage message)
			where TMessage : DnsMessageBase, new()
		{
			Task<List<TMessage>> result = SendMessageParallelAsync(message, default(CancellationToken));

			result.Wait();

			return result.Result;
		}

19 Source : ValidatorBase.cs
with Apache License 2.0
from alexreinert

public ValidationResult CheckHost(IPAddress ip, DomainName domain, string sender, bool expandExplanation = false)
		{
			var result = CheckHostInternalAsync(ip, domain, sender, expandExplanation, new State(), default(CancellationToken));
			result.Wait();

			return result.Result;
		}

See More Examples