private void Btn_start_Click(object sender, EventArgs e) { //设置按钮状态 btn_start.Enabled = false; btn_import.Enabled = false; combo_api.Enabled = false; tb_thread.Enabled = false; btn_stop.Enabled = true; lv_domains.Items.Clear(); //获取数据 currentApi = combo_api.SelectedIndex; threadCount = int.Parse(tb_thread.Text); threadSleep = int.Parse(tb_sleep.Text); threadPauseTime = int.Parse(txt_threadPause.Text); //设置flag workStarted = true; //设置变量 processedCount = 0; initStats(); UpdateProgressBar(0); //开始工作 WorkHandler handler = new WorkHandler(StartWork); handler.BeginInvoke(threadSleep, new AsyncCallback(WorkCallback), null); }
private void ExecuteMergeCommand(object cmdParam) { _otherPath = @"..\..\..\..\Resources\mergeable\E0000027FA233BE2"; //_otherPath = @"..\..\..\..\Resources\newmergeapproach\E00001D5D85ED487.0114"; LoadSubscribe(); WorkHandler.Run(Merge, MergeCallback); }
private void OpenArchive(string path, Action <PaneViewModelBase> success, Action <PaneViewModelBase, Exception> error, string password = null) { WorkHandler.Run( () => { FileManager.Open(path, password); return(true); }, result => { IsLoaded = true; Initialize(); Drive = Drives.First(); if (success != null) { success.Invoke(this); } }, exception => { if (exception is PasswordProtectedException) { //var pwd = WindowManager.ShowTextInputDialog(Resx.PasswordRequired, Resx.PleaseEnterAPassword, string.Empty, null); //if (!string.IsNullOrEmpty(pwd)) //{ // OpenArchive(path, success, error, password); // return; //} } if (error != null) { error.Invoke(this, exception); } }); }
public override void LoadDataAsync(LoadCommand cmd, LoadDataAsyncParameters cmdParam, Action <PaneViewModelBase> success = null, Action <PaneViewModelBase, Exception> error = null) { base.LoadDataAsync(cmd, cmdParam, success, error); switch (cmd) { case LoadCommand.Load: WorkHandler.Run( () => { _packageContent = (BinaryContent)cmdParam.Payload; _stfs = ModelFactory.GetModel <StfsPackage>(_packageContent.Content); return(true); }, result => { IsLoaded = true; Tabs.Add(new ProfileRebuilderTabItemViewModel(Resx.FileStructure, ParseStfs(_stfs))); SelectedTab = Tabs.First(); if (success != null) { success.Invoke(this); } }, exception => { if (error != null) { error.Invoke(this, exception); } }); break; } }
public override void LoadDataAsync(LoadCommand cmd, LoadDataAsyncParameters cmdParam, Action <PaneViewModelBase> success = null, Action <PaneViewModelBase, Exception> error = null) { base.LoadDataAsync(cmd, cmdParam, success, error); switch (cmd) { case LoadCommand.Load: case LoadCommand.Extract: case LoadCommand.Convert: WorkHandler.Run( () => { FileManager.Load((string)cmdParam.Payload); return(true); }, result => { IsLoaded = true; Initialize(); Drive = Drives.First(); if (success != null) { success.Invoke(this); } }, exception => { if (error != null) { error.Invoke(this, exception); } }); break; } }
private void ExecuteNewFolderCommand() { var items = SourcePane.Items.Select(item => item.Name).ToList(); var wkDirs = DirectoryStructure.WellKnownDirectoriesOf(SourcePane.CurrentFolder.Path); var suggestion = wkDirs.Where(d => !items.Contains(d)).Select(d => new InputDialogOptionViewModel { Value = d, DisplayName = TitleRecognizer.GetTitle(d) }).ToList(); var name = WindowManager.ShowTextInputDialog(Resx.AddNewFolder, Resx.FolderName + Strings.Colon, string.Empty, suggestion); if (name == null) { return; } name = name.Trim(); if (name == string.Empty) { WindowManager.ShowMessage(Resx.AddNewFolder, Resx.CannotCreateFolderWithNoName); return; } //var invalidChars = Path.GetInvalidFileNameChars(); //if (invalidChars.Any(name.Contains)) //{ // WindowManager.ShowMessage(Resx.AddNewFolder, Resx.CannotCreateFolderWithInvalidCharacters); // return; //} var path = string.Format("{0}{1}", SourcePane.CurrentFolder.Path, name); WorkHandler.Run(() => SourcePane.CreateFolder(path), result => NewFolderSuccess(result, name), NewFolderError); }
/// <summary> /// Unregisters handler and returns true if the named instance has been removed /// Note: it is possible to call this method on active server that is - remove handlers while serving requests /// </summary> public bool UnRegisterHandler(WorkHandler handler) { if (handler==null) return false; if (handler.Dispatcher!=this.Dispatcher) throw new WaveException(StringConsts.WRONG_DISPATCHER_HANDLER_UNREGISTRATION_ERROR.Args(handler)); return m_Handlers.Unregister(handler); }
private void ExecuteClearCacheCommand() { WorkHandler.Run(() => { WindowManager.ShowMessage(Resx.ApplicationIsBusy, Resx.PleaseWait, NotificationMessageFlags.NonClosable); _cacheManager.Clear(); return(true); }, r => WindowManager.CloseMessage()); }
/// <summary> /// Unregisters handler and returns true if the named instance has been removed /// Note: it is possible to call this method on active server that is - remove handlers while serving requests /// </summary> public bool UnRegisterHandler(WorkHandler handler) { if (handler == null) { return(false); } if (handler.Dispatcher != this.Dispatcher) { throw new WaveException(StringConsts.WRONG_DISPATCHER_HANDLER_UNREGISTRATION_ERROR.Args(handler)); } return(m_Handlers.Unregister(handler)); }
public async Task StreetsAsync(CommandContext ctx) { int change = GFRandom.Generator.NextBool() ? GFRandom.Generator.Next(1000, 5000) : -GFRandom.Generator.Next(5, 2500); using (DatabaseContext db = this.Database.CreateContext()) { await db.ModifyBankAccountAsync(ctx.User.Id, ctx.Guild.Id, b => b + change); await db.SaveChangesAsync(); } await ctx.RespondAsync(embed : new DiscordEmbedBuilder { Description = $"{ctx.Member.Mention} {WorkHandler.GetWorkStreetsString(change, this.Shared.GetGuildConfig(ctx.Guild.Id).Currency)}", Color = change > 0 ? DiscordColor.PhthaloGreen : DiscordColor.IndianRed }.WithFooter("Who needs dignity?", ctx.Member.AvatarUrl).Build()); }
public override void LoadDataAsync(LoadCommand cmd, object cmdParam) { switch (cmd) { case LoadCommand.Load: _path = (string)cmdParam; LoadSubscribe(); WorkHandler.Run(LoadFile, LoadFileCallback); break; case LoadCommand.MergeWith: //_profile.MergeWith((StfsPackage)cmdParam); break; } }
public async Task WorkAsync(CommandContext ctx) { int earned = GFRandom.Generator.Next(1000) + 1; using (DatabaseContext db = this.Database.CreateContext()) { await db.ModifyBankAccountAsync(ctx.User.Id, ctx.Guild.Id, b => b + earned); await db.SaveChangesAsync(); } await ctx.RespondAsync(embed : new DiscordEmbedBuilder { Description = $"{ctx.Member.Mention} {WorkHandler.GetWorkString(earned, this.Shared.GetGuildConfig(ctx.Guild.Id).Currency)}", Color = DiscordColor.SapGreen }.WithFooter("Arbeit macht frei.", ctx.Member.AvatarUrl).Build()); }
public void ConvertToGod(string targetPath) { var viewModel = new GodConversionSettingsViewModel(targetPath, FileManager.Details, WindowManager); if (!WindowManager.ShowGodConversionSettingsDialog(viewModel)) { return; } ProgressMessage = Resx.StartingIsoConversion + Strings.DotDotDot; ProgressValue = 0; this.NotifyProgressStarted(); WorkHandler.Run(() => ConvertToGodAsync(viewModel), ConvertToGodSuccess, ConvertToGodError); }
public async Task CrimeAsync(CommandContext ctx) { bool success = GFRandom.Generator.Next(10) == 0; int earned = success ? GFRandom.Generator.Next(10000, 100000) : -10000; using (DatabaseContext db = this.Database.CreateContext()) { await db.ModifyBankAccountAsync(ctx.User.Id, ctx.Guild.Id, b => b + earned); await db.SaveChangesAsync(); } await ctx.RespondAsync(embed : new DiscordEmbedBuilder { Description = $"{ctx.Member.Mention} {WorkHandler.GetCrimeString(earned, this.Shared.GetGuildConfig(ctx.Guild.Id).Currency)}", Color = success ? DiscordColor.SapGreen : DiscordColor.IndianRed }.WithFooter("PAYDAY3", ctx.Member.AvatarUrl).Build()); }
static int DoWork(WorkHandler del) { int retVal = 0; //after doing some work, call my delegate for (int i = 0; i < 1000; i++) { retVal += 1; continue; } return(del(new object(), new CoolEventArgs() { IsCool = true, Number = retVal })); }
public override void LoadDataAsync(LoadCommand cmd, LoadDataAsyncParameters cmdParam, Action <PaneViewModelBase> success = null, Action <PaneViewModelBase, Exception> error = null) { base.LoadDataAsync(cmd, cmdParam, success, error); switch (cmd) { case LoadCommand.Load: Initialize(); SetFavorites(); var drive = GetDriveFromPath(Settings.Directory); if (drive != null) { PathCache.Add(drive, Settings.Directory); } Drive = drive ?? GetDefaultDrive(); break; case LoadCommand.Restore: var payload = cmdParam.Payload as BinaryContent; if (payload == null) { return; } WorkHandler.Run( () => { File.WriteAllBytes(payload.FilePath, payload.Content); return(true); }, result => { if (success != null) { success.Invoke(this); } }, exception => { if (error != null) { error.Invoke(this, exception); } }); break; } }
static void Main(string[] args) { WorkHandler del1 = new WorkHandler(Delegates.WorkPerformed1); WorkHandler del2 = new WorkHandler(Delegates.WorkPerformed2); WorkHandler del3 = new WorkHandler(Delegates.WorkPerformed3); del1 += del3 + del2; int retVal = DoWork(del1); Console.WriteLine(retVal); var worker = new Worker(); worker.DoSomeWork(7); Console.Read(); }
public void StartWorkCheckValues() { var now = DateTime.UtcNow; var userId = Guid.NewGuid(); var startWorkCommand = new StartWork { TimeyTaskId = Guid.NewGuid(), WorkId = Guid.NewGuid() }; var workStarted = new WorkHandler().Handle(startWorkCommand, userId.ToString()).First() as WorkStarted; Assert.NotNull(workStarted); Assert.AreEqual(startWorkCommand.WorkId, workStarted.Id); Assert.AreEqual(startWorkCommand.TimeyTaskId, workStarted.TimeyTaskId); Assert.AreEqual(userId, workStarted.UserId); Assert.IsTrue(now < workStarted.StartTime); }
public void Recognize(FileSystemItem item, Action <int> success, Action <Exception> error) { ProgressMessage = Resx.OpeningProfile; this.NotifyProgressStarted(); WorkHandler.Run(() => RecognizeFromProfile(item), result => { this.NotifyProgressFinished(); if (success != null) { success.Invoke(result); } }, exception => { this.NotifyProgressFinished(); if (error != null) { error.Invoke(exception); } }); }
private void AsyncJob <T>(Func <T> work, Action <T> success, Action <Exception> error = null) { EventAggregator.GetEvent <AsyncJobStartedEvent>().Publish(new AsyncJobStartedEventArgs(this)); var finished = false; WorkHandler.Run( () => { Thread.Sleep(3000); return(true); }, b => { if (finished) { return; } WindowManager.ShowMessage(Resx.ApplicationIsBusy, Resx.PleaseWait, NotificationMessageFlags.NonClosable); }); WorkHandler.Run(work, b => { WindowManager.CloseMessage(); finished = true; success.Invoke(b); EventAggregator.GetEvent <AsyncJobFinishedEvent>().Publish(new AsyncJobFinishedEventArgs(this)); }, e => { WindowManager.CloseMessage(); finished = true; if (error != null) { error.Invoke(e); } EventAggregator.GetEvent <AsyncJobFinishedEvent>().Publish(new AsyncJobFinishedEventArgs(this)); }); }
static void Main(string[] args) { WorkHandler wh = DoSomething; Thread.CurrentThread.Name = "Main Thread"; var ar = wh.BeginInvoke(20, asyncResult => { Console.WriteLine("DoSomething Done"); }, null); for (int i = 0; i < 20; i++) { IntReturner ir = GetInteger; var ar2 = ir.BeginInvoke(asyncResult => { Console.WriteLine("GetInteger Done"); }, null); } int remainingWorkerThreads, remainingIOThreads; ThreadPool.GetAvailableThreads(out remainingWorkerThreads, out remainingIOThreads); Console.WriteLine($"While the worker thread is doing its work, here we are in the {Thread.CurrentThread.Name} again. Remaining threads: {remainingWorkerThreads}"); Console.ReadKey(); }
public void InitializeTransfer(Queue <QueueItem> queue, FileOperation mode) { _queue = queue; _paneCache.Clear(); _isPaused = false; _isAborted = false; _isContinued = false; _deleteAll = false; _skipAll = null; UserAction = mode; TransferAction = mode == FileOperation.Copy ? GetCopyActionText() : Resx.ResourceManager.GetString(mode.ToString()); _rememberedCopyAction = CopyAction.CreateNew; _currentFileBytesTransferred = 0; CurrentFileProgress = 0; FilesTransferred = 0; FileCount = _queue.Count; BytesTransferred = 0; TotalBytes = _queue.Where(item => item.FileSystemItem.Type == ItemType.File).Sum(item => item.FileSystemItem.Size ?? 0); Speed = 0; ElapsedTime = new TimeSpan(0); RemainingTime = new TimeSpan(0); WorkHandler.Run(BeforeTransferStart, BeforeTransferStartCallback); }
private void CheckDatabaseCallback(bool databaseExisted, Action <SanityCheckResult> callback) { var result = new SanityCheckResult(); var frameworkMessage = CheckFrameworkVersion(); if (frameworkMessage != null) { result.UserMessages = new List <NotifyUserMessageEventArgs> { frameworkMessage } } ; WorkHandler.Run(RetryFailedUserReports); if (!databaseExisted) { result.DatabaseCreated = true; WorkHandler.Run(MigrateEsentToDatabase, cacheStore => MigrateEsentToDatabaseCallback(cacheStore, callback, result)); } else { callback.Invoke(result); } }
public SessionFilter(WorkHandler handler, IConfigSectionNode confNode): base(handler, confNode) {ctor(confNode);}
public LoggingFilter(WorkHandler handler, IConfigSectionNode confNode) : base(handler, confNode) { }
public LoggingFilter(WorkHandler handler, string name, int order) : base(handler, name, order) { }
public SessionFilter(WorkHandler handler, string name, int order) : base(handler, name, order) {}
public RedirectFilter(WorkHandler handler, string name, int order) : base(handler, name, order) {}
public RedirectFilter(WorkHandler handler, IConfigSectionNode confNode): base(handler, confNode){ configureMatches(confNode); }
public GeoLookupFilter(WorkHandler handler, string name, int order) : base(handler, name, order) { }
public ErrorFilter(WorkHandler handler, string name, int order) : base(handler, name, order) { }
public ErrorFilter(WorkHandler handler, IConfigSectionNode confNode) : base(handler, confNode) { ConfigureMatches(confNode, m_ShowDumpMatches, m_LogMatches, GetType().FullName); ConfigAttribute.Apply(this, confNode); }
public GeoLookupFilter(WorkHandler handler, IConfigSectionNode confNode) : base(handler, confNode) { ctor(confNode); }
public SessionFilter(WorkHandler handler, IConfigSectionNode confNode) : base(handler, confNode) { ctor(confNode); }
public AuthorizeSessionFilter(WorkHandler handler, IConfigSectionNode confNode) : base(handler, confNode) { ConfigAttribute.Apply(this, confNode); }
public StopFilter(WorkHandler handler, IConfigSectionNode confNode): base(handler, confNode) { }
public SessionFilter(WorkHandler handler, string name, int order) : base(handler, name, order) { }
public GeoLookupFilter(WorkHandler handler, IConfigSectionNode confNode) : base(handler, confNode) { configureMatches(confNode); }
public BeforeAfterFilterBase(WorkHandler handler, string name, int order) : base(handler, name, order) { }
public BeforeAfterFilterBase(WorkHandler handler, IConfigSectionNode confNode) : base(handler, confNode) { configureMatches(confNode); }
public ErrorFilter(WorkHandler handler, IConfigSectionNode confNode): base(handler, confNode) { ConfigureMatches(confNode, m_ShowDumpMatches, m_LogMatches, GetType().FullName); ConfigAttribute.Apply(this, confNode); }
public PortalFilter(WorkHandler handler, string name, int order) : base(handler, name, order) { }