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

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

2330 Examples 7

19 View Source File : PlayerEventHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task Handle(EnreplacedyInsertedEvent<PlayerEnreplacedy> message, CancellationToken cancellationToken)
        {
            await Task.Run(() => {
               
            });
        }

19 View Source File : DigitalAnalyzerExampleViewModel.cs
License : MIT License
Project Creator : ABTSoftware

private async Task AddChannels(int digitalChannelsCount)
        {
            var digitalChannels = new List<byte[]>();

            // Force GC to free memory
            GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);

            try
            {
                // Allocate memory first
                await Task.Run(() =>
                {
                    for (var i = 0; i < digitalChannelsCount; i++)
                    {
                        var newArray = new byte[SelectedPointCount];
                        digitalChannels.Add(newArray);
                    }
                });

                // Generate random data and fill channels
                await GenerateData(digitalChannels);
            }
            catch (OutOfMemoryException)
            {
                await Application.Current.Dispatcher.BeginInvoke(new Action(() => ChannelViewModels.Clear()));
                MessageBox.Show(string.Format($"There is not enough RAM memory to allocate {SelectedChannelCount} channels with {SelectedPointCount} points each. Please select less channels or less points and try again."));
            }
            finally
            {
                OnPropertyChanged(nameof(IsEmpty));
                OnPropertyChanged(nameof(ChannelViewModels));
                OnPropertyChanged(nameof(SelectedPointCount));
                OnPropertyChanged(nameof(TotalPoints));
                OnPropertyChanged(nameof(XRange));

                IsLoading = false;
            }
        }

19 View Source File : NpcEventHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

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

19 View Source File : UserEventHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task Handle(SignUpEvent message, CancellationToken cancellationToken)
        {
            await Task.Run(() =>
            {

            });

        }

19 View Source File : PlayerQuestEventHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

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

19 View Source File : WebhookServer.cs
License : MIT License
Project Creator : 4egod

public virtual async void StartReceivingAsync()
        {
            await Task.Run(() =>
            {
                //var builder = WebHost.CreateDefaultBuilder();

                //builder.ConfigureServices(cfg =>
                //{
                //    cfg.AddRouting();
                //});

                //builder.ConfigureLogging(cfg =>
                //{
                //    //cfg.ClearProviders();
                //    //cfg.AddConsole();
                //    //cfg.AddDebug();
                //});

                //builder.UseKestrel(options =>
                //{
                //    options.Listen(IPAddress.Any, Port);
                //});

                //builder.Configure(cfg =>
                //{
                //    cfg.UseRouter(r =>
                //    {
                //        r.MapGet(WebhookTestPath, Test);
                //        r.MapGet(WebhookPath, Get);
                //        r.MapPost(WebhookPath, Post);
                //    });
                //});

                //host = builder.Build();
                //logger = host.Services.GetService<ILoggerFactory>().CreateLogger(this.GetType().ToString() + $"[{IPAddress.Any}:{Port}]");

                host.Run();
            });
        }

19 View Source File : LogManagerTests.cs
License : MIT License
Project Creator : Abc-Arbitrage

[Test]
        public void should_wait_for_event_when_log_event_pool_is_exhausted()
        {
            LogManager.Shutdown();

            BasicConfigurator.Configure(new ZeroLogBasicConfiguration
            {
                Appenders = { _testAppender },
                LogEventQueueSize = 10,
                LogEventPoolExhaustionStrategy = LogEventPoolExhaustionStrategy.WaitForLogEvent
            });

            var log = LogManager.GetLogger(typeof(LogManagerTests));

            var actualLogEvents = new List<ILogEvent>();
            for (var i = 0; i < 10; i++)
            {
                actualLogEvents.Add(log.Debug());
            }

            var signal = _testAppender.SetMessageCountTarget(2);
            var logCompletedSignal = new ManualResetEvent(false);

            Task.Run(() =>
            {
                log.Debug().Append("this is not going to happen").Log();
                logCompletedSignal.Set();
            });

            Check.That(logCompletedSignal.WaitOne(TimeSpan.FromMilliseconds(100))).IsFalse();

            actualLogEvents[0].Log();

            Check.That(logCompletedSignal.WaitOne(TimeSpan.FromMilliseconds(100))).IsTrue();
            Check.That(signal.Wait(TimeSpan.FromMilliseconds(100))).IsTrue();
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 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 View Source File : WorldViewer.cs
License : GNU General Public License v3.0
Project Creator : ACEmulator

public async void LoadLandblocks(Vector2 startBlock, Vector2 endBlock)
        {
            Buffer.ClearBuffer();
            TextureCache.Init();
            
            LScape.unload_landblocks_all();

            DungeonMode = false;

            var dx = (int)(endBlock.X - startBlock.X) + 1;
            var dy = (int)(startBlock.Y - endBlock.Y) + 1;
            var numBlocks = dx * dy;

            var size = endBlock - startBlock;
            var center = startBlock + size / 2;
            var centerX = (uint)Math.Round(center.X);
            var centerY = (uint)Math.Round(center.Y);
            var landblockID = centerX << 24 | centerY << 16 | 0xFFFF;

            MainWindow.Status.WriteLine($"Loading {numBlocks} landblocks");
            await Task.Run(() => Thread.Sleep(50));

            //Landblocks = new Dictionary<uint, R_Landblock>();
            R_Landblock r_landblock = null;
            R_Landblock centerBlock = null;

            for (var lbx = (uint)startBlock.X; lbx <= endBlock.X; lbx++)
            {
                if (lbx < 0 || lbx > 254) continue;

                for (var lby = (uint)endBlock.Y; lby <= startBlock.Y; lby++)
                {
                    if (lby < 0 || lby > 254) continue;

                    var lbid = lbx << 24 | lby << 16 | 0xFFFF;

                    var timer = Stopwatch.StartNew();
                    var landblock = LScape.get_landblock(lbid);
                    timer.Stop();

                    r_landblock = new R_Landblock(landblock);
                    //LScape.unload_landblock(lbid);

                    if (lbid == landblockID)
                        centerBlock = r_landblock;

                    MainWindow.Status.WriteLine($"Loaded {lbid:X8} in {timer.Elapsed.TotalMilliseconds}ms");

                    //Landblocks.Add(lbid, new R_Landblock(landblock));
                }
            }

            Buffer.BuildBuffers();

            Camera.InitLandblock(centerBlock);
            GameView.ViewMode = ViewMode.World;

            FreeResources();
        }

19 View Source File : Form1.cs
License : MIT License
Project Creator : 2881099

private void buttonItem16_Click(object sender, EventArgs e)
        {
            Task.Run(() => LoadDataTreeList());
        }

19 View Source File : UserEventHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task Handle(VisitedEvent message, CancellationToken cancellationToken)
        {
            await Task.Run(() =>
            {

            });
        }

19 View Source File : UserEventHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task Handle(EnreplacedyInsertedEvent<UserEnreplacedy> message, CancellationToken cancellationToken)
        {
            await Task.Run(() =>
            {

            });
        }

19 View Source File : WebhookServerBase.cs
License : MIT License
Project Creator : 4egod

public virtual async void StartReceivingAsync()
        {
            await Task.Run(() =>
            {
                #region Unused
                //var builder = WebHost.CreateDefaultBuilder();

                //builder.ConfigureServices(cfg =>
                //{
                //    cfg.AddRouting();
                //});

                //builder.ConfigureLogging(cfg =>
                //{
                //    //cfg.ClearProviders();
                //    //cfg.AddConsole();
                //    //cfg.AddDebug();
                //});

                //builder.UseKestrel(options =>
                //{
                //    options.Listen(IPAddress.Any, Port);
                //});

                //builder.Configure(cfg =>
                //{
                //    cfg.UseRouter(r =>
                //    {
                //        r.MapGet(WebhookTestPath, Test);
                //        r.MapGet(WebhookPath, Get);
                //        r.MapPost(WebhookPath, Post);
                //    });
                //});

                //host = builder.Build();
                //logger = host.Services.GetService<ILoggerFactory>().CreateLogger(this.GetType().ToString() + $"[{IPAddress.Any}:{Port}]");
                #endregion

                Host.Run();
            });
        }

19 View Source File : NpcEventHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task Handle(EnreplacedyUpdatedEvent<NpcEnreplacedy> message, CancellationToken cancellationToken)
        {
            var key = string.Format(CacheKey.Npc, message.Enreplacedy.Id);

            await Task.Run(() => {
                _cache.Remove(key);
            });
        }

19 View Source File : Net40.cs
License : MIT License
Project Creator : 2881099

public static Task Run(Action action)
        {
#if net40
            var tcs = new TaskCompletionSource<object>();
            new Thread(() =>
            {
                try
                {
                    action();
                    tcs.SetResult(null);
                }
                catch (Exception ex)
                {
                    tcs.SetException(ex);
                }
            })
            { IsBackground = true }.Start();
            return tcs.Task;
#else
            return Task.Run(action);
#endif
        }

19 View Source File : PlayerQuestEventHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task Handle(EnreplacedyDeletedEvent<PlayerQuestEnreplacedy> message, CancellationToken cancellationToken)
        {
            var key = string.Format(CacheKey.PlayerQuestList, message.Enreplacedy.PlayerId);
            await Task.Run(() => {
                _cache.Remove(key);
            });
        }

19 View Source File : Repository.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public virtual async Task Update(TEnreplacedy obj, bool saveChanges = false)
        {
            await Task.Run(() => {
                _dbSet.Update(obj);
            });


            if (saveChanges)
            {
                await SaveChanges();
            }
        }

19 View Source File : WaitForBackgroundThread.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public ConfiguredTaskAwaitable.ConfiguredTaskAwaiter GetAwaiter()
        {
            return Task.Run(() => { }).ConfigureAwait(false).GetAwaiter();
        }

19 View Source File : UserLock.cs
License : Apache License 2.0
Project Creator : 0xFireball

public async Task ObtainConcurrentReadAsync()
        {
            await Task.Run(() => ObtainConcurrentRead());
        }

19 View Source File : DatabasePerfTest.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void RunAsync(Session session, int biotasPerTest = DefaultBiotasTestCount)
        {
            Task.Run(() => Run(session, biotasPerTest));
        }

19 View Source File : PlayerEventHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task Handle(EnreplacedyDeletedEvent<PlayerEnreplacedy> message, CancellationToken cancellationToken)
        {
            await Task.Run(() =>
            {

            });
        }

19 View Source File : RoomEventHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

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

19 View Source File : LocalStorageHandler.cs
License : Apache License 2.0
Project Creator : 0xFireball

public async Task DeleteFileAsync(string fileId)
        {
            replacedertIdenreplacedyProvided(); // Quota is affected
            var filePath = GetTargetFilePath(fileId);
            var fileInfo = await Task.Run(() => new FileInfo(filePath));
            var fileSize = fileInfo.Length;
            await Task.Run(() => File.Delete(filePath));
            if (_owner != null)
            {
                var lockEntry = ServerContext.ServiceTable[_owner].UserLock;
                // Decrease user storage usage
                await lockEntry.ObtainExclusiveWriteAsync();
                var userManager = new WebUserManager(ServerContext);
                var ownerData = await userManager.FindUserByUsernameAsync(_owner);
                var prevStorageUsage = ownerData.StorageUsage;
                ownerData.StorageUsage -= fileSize;
                await userManager.UpdateUserInDatabaseAsync(ownerData);
                lockEntry.ReleaseExclusiveWrite();
            }
        }

19 View Source File : RoomEventHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

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

19 View Source File : MainFormHandler.cs
License : GNU General Public License v3.0
Project Creator : 2dust

public void UpdateTask(Config config, Action<bool, string> update)
        {
            _updateUI = update;
            Task.Run(() => UpdateTaskRun(config));
        }

19 View Source File : UserEventHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task Handle(EnreplacedyDeletedEvent<UserEnreplacedy> message, CancellationToken cancellationToken)
        {
            await Task.Run(() =>
            {

            });
        }

19 View Source File : Repository.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public virtual async Task Remove(TEnreplacedy obj, bool saveChanges = false)
        {
            await Task.Run(() => {
                _dbSet.Remove(obj);
            });


            if (saveChanges)
            {
                await SaveChanges();
            }
        }

19 View Source File : TrainCaching.cs
License : MIT License
Project Creator : 42skillz

public async Task Save(string train, Train trainInst, string bookingRef)
        {
            await Task.Run((Action) (() => Cache(trainInst, train, bookingRef)));
        }

19 View Source File : UserEventHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task Handle(SignInEvent message, CancellationToken cancellationToken)
        {
            await Task.Run(() =>
            {

            });
        }

19 View Source File : DbContext.cs
License : Apache License 2.0
Project Creator : 1448376744

public async Task BeginTransactionAsync(IsolationLevel level)
        {
            await Task.Run(() =>
            {
                _transaction = Connection.BeginTransaction(level);
                Logging?.Invoke("Begin Transaction IsolationLevel = " + level);
            });
        }

19 View Source File : UserEventHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task Handle(SignOutEvent message, CancellationToken cancellationToken)
        {
            await Task.Run(() =>
            {

            });
        }

19 View Source File : WebhookServer.cs
License : MIT License
Project Creator : 4egod

private async void WebhookServer_PostReceived(WebhookEventArgs e)
        {
            try
            {
#if !DEBUG
                const string signatureHeader = "X-Twitter-Webhooks-Signature";
                
                if (!e.Request.Headers.Keys.Contains(signatureHeader))
                {
                    Logger.LogWarning(Resources.InvalidSignature);

                    InvalidPostReceived?.Invoke(e);

                    return;
                }

                var signature = e.Request.Headers[signatureHeader][0];

                if (!VerifySignature(signature, e.BodyRaw))
                {
                    Logger.LogWarning(Resources.InvalidSignature);

                    InvalidPostReceived?.Invoke(e);

                    return;
                }
#endif
                e.IsValid = true;

                if (Recipient != 0)
                {
                    RecipientChecker check = e.Body.FromJson<RecipientChecker>();

                    if (Recipient != check.Recipient) return;
                }

                WebhookEvent webhookEvent = e.Body.FromJson<WebhookEvent>();

                if (webhookEvent.DirectMessageEvents != null)
                {
                    if (OnMessage != null)
                    {
                        foreach (var item in webhookEvent.DirectMessageEvents)
                        {
                            MessageEventArgs args = new MessageEventArgs()
                            {
                                Recipient = webhookEvent.Recipient,
                                Message = item.ToMessage()
                            };

                            await Task.Run(() =>
                            {
                                OnMessage.Invoke(args);
                            });
                        }
                    }
                }

                if (webhookEvent.FollowEvents != null)
                {
                    foreach (var item in webhookEvent.FollowEvents)
                    {
                        if (item.Type == "follow" && OnFollow != null)
                        {
                            FollowEventArgs args = new FollowEventArgs()
                            {
                                Recipient = webhookEvent.Recipient,
                                Timestamp = item.Timestamp,
                                Type = FollowType.Follow,
                                Target = item.Target,
                                Source = item.Source
                            };

                            await Task.Run(() =>
                            {
                                OnFollow.Invoke(args);
                            });
                        }

                        if (item.Type == "unfollow" && OnUnFollow != null)
                        {
                            FollowEventArgs args = new FollowEventArgs()
                            {
                                Recipient = webhookEvent.Recipient,
                                Timestamp = item.Timestamp,
                                Type = FollowType.Unfollow,
                                Target = item.Target,
                                Source = item.Source
                            };

                            await Task.Run(() =>
                            {
                                OnUnFollow.Invoke(args);
                            });
                        }
                    }
                }

                if (webhookEvent.TweetCreateEvents != null)
                {
                    foreach (var item in webhookEvent.TweetCreateEvents)
                    {
                        TweetEventArgs args = new TweetEventArgs()
                        {
                            Recipient = webhookEvent.Recipient,
                            Tweet = item
                        };

                        bool processed = false;

                        if (item.RetweetedFrom != null)
                        {
                            if (OnRetweet != null)
                            {
                                await Task.Run(() =>
                                {
                                    OnRetweet.Invoke(args);
                                });
                            }

                            processed = true;
                        }

                        if (item.QuotedFrom != null)
                        {
                            if (OnQuote != null)
                            {
                                await Task.Run(() =>
                                {
                                    OnQuote.Invoke(args);
                                });
                            }

                            processed = true;
                        }

                        if (item.ReplyToUserId != null && item.ReplyToStatusId != null)
                        { 
                            if (OnComment != null)
                            {
                                await Task.Run(() =>
                                {
                                    OnComment.Invoke(args);
                                });
                            }

                            processed = true;
                        }

                        if (item.ReplyToUserId != null && item.ReplyToStatusId == null)
                        {
                            if (OnMention != null)
                            {
                                await Task.Run(() =>
                                {
                                    OnMention.Invoke(args);
                                });
                            }

                            processed = true;
                        }

                        if (!processed)
                        {
                            if (OnTweet != null)
                            {
                                await Task.Run(() =>
                                {
                                    OnTweet.Invoke(args);
                                });
                            }
                        }
                    }

                    #region 
                    //if (Tweeted != null)
                    //{
                    //    foreach (var item in webhookEvent.TweetCreateEvents)
                    //    {
                    //        TweetCreateEventArgs args = new TweetCreateEventArgs()
                    //        {
                    //            Tweet = item
                    //        };

                    //        Tweeted.Invoke(args);
                    //    }
                    //}
                    #endregion
                }

                if (webhookEvent.LikeEvents != null)
                {
                    if (OnLike != null)
                    {
                        foreach (var item in webhookEvent.LikeEvents)
                        {
                            LikeEventArgs args = new LikeEventArgs()
                            {
                                Recipient = webhookEvent.Recipient,
                                Id = item.Id,
                                Timestamp = item.Timestamp,
                                Tweet = item.Tweet,
                                User = item.User
                            };

                            await Task.Run(() =>
                            {
                                OnLike.Invoke(args);
                            });  
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(EventId, ex, ex.Message);
            }
        }

19 View Source File : NpcEventHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

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

19 View Source File : LocalStorageHandler.cs
License : Apache License 2.0
Project Creator : 0xFireball

public async Task<FileUploadResult> HandleUploadAsync(string fileName, Stream stream)
        {
            replacedertIdenreplacedyProvided(); // Quota is affected
            var fileId = Guid.NewGuid().ToString();
            var targetFile = GetTargetFilePath(fileId);
            var uploadStreamFileSize = stream.Length;

            try
            {
                // Write file (Wait for upload throttle)
                await ServerContext.ServiceTable[_owner]
                    .UploadThrottle.WithResourceAsync(async () =>
                    {
                        using (var destinationStream = File.Create(targetFile))
                        {
                            await stream.CopyToAsync(destinationStream);
                        }
                    });

                // Make sure user has enough space remaining
                if (_owner != null)
                {
                    var lockEntry = ServerContext.ServiceTable[_owner].UserLock;
                    await lockEntry.ObtainExclusiveWriteAsync();
                    var userManager = new WebUserManager(ServerContext);
                    var ownerData = await userManager.FindUserByUsernameAsync(_owner);
                    var afterUploadSpace = ownerData.StorageUsage + uploadStreamFileSize;
                    if (afterUploadSpace > ownerData.StorageQuota)
                    {
                        lockEntry.ReleaseExclusiveWrite();
                        // Throw exception, catch block will remove file and rethrow
                        throw new QuotaExceededException();
                    }
                    // Increase user storage usage
                    ownerData.StorageUsage += uploadStreamFileSize;
                    await userManager.UpdateUserInDatabaseAsync(ownerData);
                    lockEntry.ReleaseExclusiveWrite();
                }
            }
            catch (QuotaExceededException)
            {
                // Roll back write
                await Task.Run(() => File.Delete(targetFile));
                throw;
            }

            return new FileUploadResult
            {
                FileId = fileId,
                Size = uploadStreamFileSize
            };
        }

19 View Source File : PlayerQuestEventHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task Handle(EnreplacedyInsertedEvent<PlayerQuestEnreplacedy> message, CancellationToken cancellationToken)
        {
            var key = string.Format(CacheKey.PlayerQuestList, message.Enreplacedy.PlayerId);
            await Task.Run(() => {
                _cache.Remove(key);
            });
        }

19 View Source File : OtherExpressions.cs
License : MIT License
Project Creator : 71

[Fact]
        public void ShouldLockExecution()
        {
            object syncRoot = new object();
            Expression syncRootEx = syncRoot.AsExpression();

            Expression sleep = X.Express<Action>(() => Thread.Sleep(2000));

            Action compiledAction = Expression
                .Lambda<Action>(X.Lock(syncRootEx, sleep))
                .Compile();

            Task task = Task.Run(compiledAction);

            // Sleep to make sure the task has the time to start running
            while (task.Status != TaskStatus.Running)
                Thread.Sleep(50);

            DateTime beforeEntering = DateTime.Now;

            lock (syncRoot)
                DateTime.Now.ShouldBeGreaterThan(beforeEntering.AddMilliseconds(1000));
        }

19 View Source File : UserEventHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task Handle(EnreplacedyUpdatedEvent<UserEnreplacedy> message, CancellationToken cancellationToken)
        {
            await Task.Run(() =>
            {

            });
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 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 View Source File : ProcessExtensions.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public static async Task<ProcessResult> StartProcessAsync(this Process process, ProcessStartInfo startInfo, bool showDebug = false, CancellationToken cancellationToken = default)
        {
            Debug.replacedert(!startInfo.UseShellExecute, "Process Start Info must not use shell execution.");
            Debug.replacedert(startInfo.RedirectStandardOutput, "Process Start Info must redirect standard output.");
            Debug.replacedert(startInfo.RedirectStandardError, "Process Start Info must redirect standard errors.");

            process.StartInfo = startInfo;
            process.EnableRaisingEvents = true;

            var processResult = new TaskCompletionSource<ProcessResult>();
            var errorCodeResult = new TaskCompletionSource<string[]>();
            var errorList = new List<string>();
            var outputCodeResult = new TaskCompletionSource<string[]>();
            var outputList = new List<string>();

            process.Exited += OnProcessExited;
            process.ErrorDataReceived += OnErrorDataReceived;
            process.OutputDataReceived += OnOutputDataReceived;

            async void OnProcessExited(object sender, EventArgs args)
            {
                processResult.TrySetResult(new ProcessResult(process.ExitCode, await errorCodeResult.Task, await outputCodeResult.Task));
                process.Close();
                process.Dispose();
            }

            void OnErrorDataReceived(object sender, DataReceivedEventArgs args)
            {
                if (args.Data != null)
                {
                    errorList.Add(args.Data);

                    if (!showDebug)
                    {
                        return;
                    }

                    UnityEngine.Debug.LogError(args.Data);
                }
                else
                {
                    errorCodeResult.TrySetResult(errorList.ToArray());
                }
            }

            void OnOutputDataReceived(object sender, DataReceivedEventArgs args)
            {
                if (args.Data != null)
                {
                    outputList.Add(args.Data);

                    if (!showDebug)
                    {
                        return;
                    }

                    UnityEngine.Debug.Log(args.Data);
                }
                else
                {
                    outputCodeResult.TrySetResult(outputList.ToArray());
                }
            }

            if (!process.Start())
            {
                if (showDebug)
                {
                    UnityEngine.Debug.LogError("Failed to start process!");
                }

                processResult.TrySetResult(new ProcessResult(process.ExitCode, new[] { "Failed to start process!" }, null));
            }
            else
            {
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                CancellationWatcher(process);
            }

            async void CancellationWatcher(Process _process)
            {
                await Task.Run(() =>
                {
                    try
                    {
                        while (!_process.HasExited)
                        {
                            if (cancellationToken.IsCancellationRequested)
                            {
                                _process.Kill();
                            }
                        }
                    }
                    catch
                    {
                        // ignored
                    }
                });
            }

            return await processResult.Task;
        }

19 View Source File : SmtpMail.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task Send(MailModel message)
        {
            await Task.Run(() =>
            {
                try
                {
                    SmtpClient client = new SmtpClient(_appConfig.Email.SmtpServer, _appConfig.Email.SmtpPort);
                    client.UseDefaultCredentials = false;
                    client.Credentials = new NetworkCredential(_appConfig.Email.AccountName, _appConfig.Email.Preplacedword);
                    MailMessage mailMessage = new MailMessage();
                    mailMessage.From = new MailAddress(_appConfig.Email.AccountName, _appConfig.Email.FromAlias);
                    mailMessage.To.Add(message.Address);
                    mailMessage.Body = message.Content;
                    mailMessage.Subject = message.Subject;
                    mailMessage.IsBodyHtml = true;
                    client.Send(mailMessage);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "SendEmail Exception");
                    throw ex;
                }

            }).ConfigureAwait(false);
        }

19 View Source File : DigitalAnalyzerExampleViewModel.cs
License : MIT License
Project Creator : ABTSoftware

private async Task AddChannels(int digitalChannelsCount, int replacedogChannelsCount)
        {
            List<byte[]> digitalChannels = new List<byte[]>();
            List<float[]> replacedogChannels = new List<float[]>();

            // Force GC to free memory
            GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);

            try
            {
                // Allocate memory first
                await Task.Run(() =>
                {
                    for (var i = 0; i < digitalChannelsCount; i++)
                    {
                        var newArray = new byte[SelectedPointCount];
                        digitalChannels.Add(newArray);
                    }

                    for (var i = 0; i < replacedogChannelsCount; i++)
                    {
                        var newArray = new float[SelectedPointCount];
                        replacedogChannels.Add(newArray);
                    }
                });

                // Generate random data and fill channels
                await GenerateData(digitalChannels, replacedogChannels);
            }
            catch (OutOfMemoryException)
            {
                await Application.Current.Dispatcher.BeginInvoke(new Action(() => ChannelViewModels.Clear()));
                MessageBox.Show(string.Format($"There is not enough RAM memory to allocate {SelectedChannelCount} channels with {SelectedPointCount} points each. Please select less channels or less points and try again."));
            }
            finally
            {
                OnPropertyChanged(nameof(IsEmpty));
                OnPropertyChanged(nameof(ChannelViewModels));
                OnPropertyChanged(nameof(SelectedPointCount));
                OnPropertyChanged(nameof(TotalPoints));
                OnPropertyChanged(nameof(XRange));

                IsLoading = false;
            }
        }

19 View Source File : UserLock.cs
License : Apache License 2.0
Project Creator : 0xFireball

public async Task ObtainExclusiveWriteAsync()
        {
            await Task.Run(() => ObtainExclusiveWrite());
        }

19 View Source File : AscReader.cs
License : MIT License
Project Creator : ABTSoftware

public static async Task<AscData> ReadFileToAscData(
            string filename, Func<float, Color> colorMapFunction, Action<int> reportProgress = null)
        {
            AscData result = new AscData()
            {
                XValues = new List<float>(),
                YValues = new List<float>(),
                ZValues = new List<float>(),
                ColorValues = new List<Color>(),
            };

            await Task.Run(() =>
            {
                using (var file = File.OpenText(filename))
                {
                    // Load the ASC file format 
                    result.NumberColumns = ReadInt(file, "ncols");
                    result.NumberRows = ReadInt(file, "nrows");
                    result.XllCorner = ReadInt(file, "xllcorner");
                    result.YllCorner = ReadInt(file, "yllcorner");
                    result.CellSize = ReadInt(file, "cellsize");
                    result.NoDataValue = ReadInt(file, "NODATA_value");

                    // Generate X-values based off cell position 
                    float[] xValuesRow = Enumerable.Range(0, result.NumberColumns).Select(x => (float)x * result.CellSize).ToArray();

                    for (int i = 0; i < result.NumberRows; i++)
                    {
                        // Read heights from the ASC file and generate Z-cell values
                        float[] heightValuesRow = ReadFloats(file, " ", result.NoDataValue);
                        float[] zValuesRow = Enumerable.Repeat(0 + i * result.CellSize, result.NumberRows).Select(x => (float)x).ToArray();

                        result.XValues.AddRange(xValuesRow);
                        result.YValues.AddRange(heightValuesRow);
                        result.ZValues.AddRange(zValuesRow);

                        if (colorMapFunction != null)
                        {
                            // Optional color-mapping of points based on height 
                            Color[] colorValuesRow = heightValuesRow
                                .Select(colorMapFunction)
                                .ToArray();
                            result.ColorValues.AddRange(colorValuesRow);
                        }

                        // Optional report loading progress 0-100%
                        reportProgress?.Invoke((int)(100.0f * i / result.NumberRows));
                    }
                }
            });

            return result;
        }

19 View Source File : PlayerEventHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task Handle(EnreplacedyUpdatedEvent<PlayerEnreplacedy> message, CancellationToken cancellationToken)
        {
            await Task.Run(() =>
            {

            });
        }

19 View Source File : Form1.cs
License : MIT License
Project Creator : 2881099

private void Form1_Load(object sender, EventArgs e)
        {
            Task.Run(() => LoadDataTreeList());
            // DesktopAlert.Show("发现新版本", "\uf005", eSymbolSet.Awesome, Color.Empty, eDesktopAlertColor.DarkRed, eAlertPosition.BottomRight, 5, 0, (x) => { });
            this.WindowState = FormWindowState.Maximized;
        }

19 View Source File : ResourceThrottle.cs
License : Apache License 2.0
Project Creator : 0xFireball

public async Task AcquireAsync()
        {
            await Task.Run(() => Acquire());
        }

19 View Source File : UserLock.cs
License : Apache License 2.0
Project Creator : 0xFireball

public async Task ObtainExclusiveReadAsync()
        {
            await Task.Run(() => ObtainExclusiveRead());
        }

19 View Source File : DbContext.cs
License : Apache License 2.0
Project Creator : 1448376744

public async Task BeginTransactionAsync()
        {
            await Task.Run(() =>
            {
                _transaction = Connection.BeginTransaction();
                Logging?.Invoke("Begin Transaction");
            });
        }

19 View Source File : AssetManager.cs
License : MIT License
Project Creator : 404Lcc

private async Task<replacedetData> LoadreplacedetDataAsync<T>(string name, string suffix, bool isKeep, bool isreplacedetBundle, params string[] types) where T : Object
        {
            await Task.Run(() => { });
            string path = GetreplacedetPath(name, types);
            if (replacedetDict.ContainsKey(path))
            {
                return replacedetDict[path];
            }
            else
            {
                replacedetData replacedetData = new replacedetData();
                Object replacedet = null;
#if replacedetBundle
                if (isreplacedetBundle)
                {
#if !UNITY_EDITOR
                    AsyncOperationHandle<T> handler = Addressables.LoadreplacedetAsync<T>($"replacedets/Bundles/{path}{suffix}");
                    await handler.Task;
                    replacedet = handler.Result;
#else
                    replacedet = replacedetDatabase.LoadreplacedetAtPath<T>($"replacedets/Bundles/{path}{suffix}");
#endif
                }
                else
                {
#if !UNITY_EDITOR
                    replacedet = Resources.Load<T>(path);
#else
                    replacedet = replacedetDatabase.LoadreplacedetAtPath<T>($"replacedets/Resources/{path}{suffix}");
#endif
                }
#else
#if !UNITY_EDITOR
                replacedet = Resources.Load<T>(path);
#else
                replacedet = replacedetDatabase.LoadreplacedetAtPath<T>($"replacedets/Resources/{path}{suffix}");
#endif
#endif
                if (replacedet == null) return null;
                replacedetData.replacedet = replacedet;
                replacedetData.types = types;
                replacedetData.name = name;
                replacedetData.suffix = suffix;
                replacedetData.isKeep = isKeep;
                replacedetData.isreplacedetBundle = isreplacedetBundle;
                replacedetDict.Add(path, replacedetData);
                return replacedetData;
            }
        }

19 View Source File : RoomEventHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

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

See More Examples