public static void Main(string[] args) { Application.SetHighDpiMode(HighDpiMode.SystemAware); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); AsynchronousAction = new AsynchronousAction(); Thread t = new Thread(() => { Application.Run(new MainMenu()); }); t.IsBackground = true; t.Start(); AllocConsole(); consolePointer = GetConsoleWindow(); HideConsole(); while (t.IsAlive) { Thread.Sleep(100); AsynchronousAction.AsynchronousInvokeAndDestroy(); } }
public LoadingMenu() { InitializeComponent(); Timer1InvokeAndDestroyTickAction = new AsynchronousAction(); Timer1TickAction = new AsynchronousAction(); }
public void PrecededByTest1() { int invokedCount1 = 0; int invokedCount2 = 0; int sequence = 7; int invokedCount1Sequence = 0; int invokedCount2Sequence = 0; AsyncContinuation originalContinuation = ex => { invokedCount1++; invokedCount1Sequence = sequence++; }; AsynchronousAction doSomethingElse = c => { invokedCount2++; invokedCount2Sequence = sequence++; c(null); c(null); }; AsyncContinuation cont = AsyncHelpers.PrecededBy(originalContinuation, doSomethingElse); cont(null); // make sure doSomethingElse was invoked first // then original continuation Assert.Equal(7, invokedCount2Sequence); Assert.Equal(8, invokedCount1Sequence); Assert.Equal(1, invokedCount1); Assert.Equal(1, invokedCount2); }
public void PrecededByTest2() { int invokedCount1 = 0; int invokedCount2 = 0; int sequence = 7; int invokedCount1Sequence = 0; int invokedCount2Sequence = 0; AsyncContinuation originalContinuation = ex => { invokedCount1++; invokedCount1Sequence = sequence++; }; AsynchronousAction doSomethingElse = c => { invokedCount2++; invokedCount2Sequence = sequence++; c(null); c(null); }; AsyncContinuation cont = AsyncHelpers.PrecededBy(originalContinuation, doSomethingElse); var sampleException = new InvalidOperationException("Some message."); cont(sampleException); // make sure doSomethingElse was not invoked Assert.Equal(0, invokedCount2Sequence); Assert.Equal(7, invokedCount1Sequence); Assert.Equal(1, invokedCount1); Assert.Equal(0, invokedCount2); }
private void InsertOnLogListBox(string text) { Timer1TickAction += () => { logListBox.Items.Add(text); logListBox.SelectedItem = text; }; }
public GameLauncher() { InitializeComponent(); Parameter.Initialize(); TickAction = new AsynchronousAction(); launcherRequestManager = new LauncherRequestManager(); txtNickname.Text = Parameter.GameClientSettingsInformation.SavedNickname; }
public SignUpForm() { InitializeComponent(); #if DEBUG btnRegisterDebug.Visible = true; btnRegisterDebug.Enabled = true; #endif TickAction = new AsynchronousAction(); }
/// <summary> /// Runs the specified asynchronous action synchronously (blocks until the continuation has /// been invoked). /// </summary> /// <param name="action">The action.</param> /// <remarks> /// Using this method is not recommended because it will block the calling thread. /// </remarks> public static void RunSynchronously(AsynchronousAction action) { var ev = new ManualResetEvent(false); Exception lastException = null; action(PreventMultipleCalls(ex => { lastException = ex; ev.Set(); })); ev.WaitOne(); if (lastException != null) { throw new NLogRuntimeException("Asynchronous exception has occurred.", lastException); } }
private void OnStartUnpackingPatch(PatchHistory patch) { Timer1TickAction += () => { InsertOnLogListBox($"{Language.Patching2Unpacking} {patch.BuildPatchPath}"); UpdateMenuLabels(MenuState.Unpacking, new Dictionary<string, string>() { { "patchname", $"{patch.PatchVersionName} - {patch.BuildPatchPath}" } }); }; }
public GameLauncher(string[] args) { InitializeComponent(); Parameter.Initialize(args); TickAction = new AsynchronousAction(); nicknameTextBox.Text = Parameter.GameClientSettingsInformation.SavedNickname; versionLabel.Text = Parameter.GameClientSettingsInformation.ClientVersionHistory.PatchVersionName; //Disable Login Button SetEnableTextBox(true); btnLogin.Enabled = false; }
protected override void given_the_context_of() { method = Mock <IMethod>(); method.Stub(x => x.Info).Return(typeof(object).GetMethod("ToString")).Repeat.Any(); messageBinder = Mock <IMessageBinder>(); filterManager = Stub <IFilterManager>(); action = new AsynchronousAction( Stub <IServiceLocator>(), method, messageBinder, filterManager, false ); }
protected override void given_the_context_of() { method = Mock<IMethod>(); method.Stub(x => x.Info).Return(typeof(object).GetMethod("ToString")).Repeat.Any(); messageBinder = Mock<IMessageBinder>(); filterManager = Stub<IFilterManager>(); action = new AsynchronousAction( Stub<IServiceLocator>(), method, messageBinder, filterManager, false ); }
private static AsynchronousAction ExceptionGuard(AsynchronousAction action) { return(cont => { try { action(cont); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } cont(exception); } }); }
private static AsynchronousAction <T> ExceptionGuard <T>(AsynchronousAction <T> action) { return((T argument, AsyncContinuation cont) => { try { action(argument, cont); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } cont(exception); } }); }
private void OnFinalizeDownloadingFile(Queue<Action> actionQueue, PatchHistory patchHistory) { Timer1TickAction += new Action(() => { InsertOnLogListBox($"{Language.Patching3Downloading} {patchHistory.BuildPatchPath}"); currentDownloadedFile++; totalProgressBar.Value = (int)Math.Ceiling(100 * (currentDownloadedFile / (float)patchesToBeDownloaded.Count)); if (actionQueue.Count > 0) { actionQueue.Dequeue().Invoke(); } else { StartUnpackingFiles(); } }); }
private void HaltPatchingProcess(Exception exception = null) { Timer1TickAction.Clear(); Timer1TickAction += () => { InsertOnLogListBox($"{Language.GameUpdaterLabel4Error}"); if (exception != null) { InsertOnLogListBox($"{Language.GameUpdaterLabel5Error} {exception.Message}"); if (exception.InnerException != null && exception.Message != exception.InnerException.Message) { InsertOnLogListBox($"{Language.GameUpdaterLabel6Error} {exception.InnerException.Message}"); } } timer2.Enabled = false; }; }
public GameUpdater(PatchHistory serverPatchHistory) { InitializeComponent(); Timer1TickAction = new AsynchronousAction(); Timer2TickAction = new AsynchronousAction(); shouldShowLog = true; interfaceLabels = new Label[] { downloadLabel1, downloadLabel2, downloadLabel3 }; currentPatchEntry = Parameter.GameClientSettingsInformation.ClientVersionHistory; patchesToBeDownloaded = serverPatchHistory.PatchHistoryList.Union(new List<PatchHistory> { serverPatchHistory }) .Where((x) => x.CreationDate > currentPatchEntry.CreationDate) .OrderBy((x) => x.CreationDate).ToList(); UpdateMenuLabels(MenuState.ReadyToDownload); InsertOnLogListBox(Language.Patching1Ready); }
private void OnUnpackPatch(PatchHistory patch, bool isMD5Valid, Exception exception) { Timer1TickAction += () => { int current = patchesToBeDownloaded.IndexOf(patch); int total = patchesToBeDownloaded.Count; totalProgressBar.Value = currentProgressBar.Value = 100 * ((current + 1) / total); if (exception != null) { InsertOnLogListBox($"{Language.Patching1ExceptionUnpack} {patch.BuildPatchPath}"); InsertOnLogListBox($"{Language.Patching2ExceptionUnpack}"); HaltPatchingProcess(exception); } else if (!isMD5Valid) { InsertOnLogListBox($"{Language.Patching1ExceptionUnpack} {patch.BuildPatchPath}"); InsertOnLogListBox($"{Language.Patching3ExceptionUnpack}"); HaltPatchingProcess(); } else { InsertOnLogListBox($"{Language.Patching3Unpacking} {patch.BuildPatchPath}"); } if (patchesToBeDownloaded.Last() == patch) { timer2.Enabled = true; InsertOnLogListBox($"{Language.Patching2Done}"); DateTime date = DateTime.Now; CloseClientAndApplyPatchTickAction(date); } }; }
private void OnReceiveData(string filename, int downloadedFiles, float downloadPercentage, long receivedBytes, long totalBytes, DateTime downloadStartTime) { Timer1TickAction += () => { double totalElapsedSeconds = Math.Max(1, (DateTime.Now - downloadStartTime).TotalSeconds); float totalReceivedMB = ((receivedBytes / 1024f) / 1024f); float maxSizeMB = ((totalBytes / 1024f) / 1024f); float remainingMB = maxSizeMB - totalReceivedMB; UpdateMenuLabels(MenuState.Downloading, new Dictionary<string, string>() { { "filename", filename }, { "current", $"{downloadedFiles + 1}" }, { "total", $"{patchesToBeDownloaded.Count}" }, { "remaining", remainingMB.ToString("0.##") }, { "downloaded", totalReceivedMB.ToString("0.##") }, { "speed", (totalReceivedMB / totalElapsedSeconds).ToString("0.##") } }); currentProgressBar.Value = Math.Min((int)downloadPercentage, 100); }; }
/// <summary> /// Iterates over all items in the given collection and runs the specified action /// in sequence (each action executes only after the preceding one has completed without an error). /// </summary> /// <typeparam name="T">Type of each item.</typeparam> /// <param name="items">The items to iterate.</param> /// <param name="asyncContinuation">The asynchronous continuation to invoke once all items /// have been iterated.</param> /// <param name="action">The action to invoke for each item.</param> public static void ForEachItemSequentially <T>(IEnumerable <T> items, AsyncContinuation asyncContinuation, AsynchronousAction <T> action) { action = ExceptionGuard(action); AsyncContinuation invokeNext = null; IEnumerator <T> enumerator = items.GetEnumerator(); invokeNext = ex => { if (ex != null) { asyncContinuation(ex); return; } if (!enumerator.MoveNext()) { enumerator.Dispose(); asyncContinuation(null); return; } action(enumerator.Current, PreventMultipleCalls(invokeNext)); }; invokeNext(null); }
/// <summary> /// Modifies the continuation by pre-pending given action to execute just before it. /// </summary> /// <param name="asyncContinuation">The async continuation.</param> /// <param name="action">The action to pre-pend.</param> /// <returns>Continuation which will execute the given action before forwarding to the actual continuation.</returns> public static AsyncContinuation PrecededBy(AsyncContinuation asyncContinuation, AsynchronousAction action) { return(PrecededBy(null, asyncContinuation, action)); }
/// <summary> /// Iterates over all items in the given collection and runs the specified action /// in sequence (each action executes only after the preceding one has completed without an error). /// </summary> /// <typeparam name="T">Type of each item.</typeparam> /// <param name="items">The items to iterate.</param> /// <param name="asyncContinuation">The asynchronous continuation to invoke once all items /// have been iterated.</param> /// <param name="action">The action to invoke for each item.</param> public static void ForEachItemSequentially <T>(IEnumerable <T> items, AsyncContinuation asyncContinuation, AsynchronousAction <T> action) { ForEachItemInParallel(null, items, asyncContinuation, action); }
/// <summary> /// Runs the specified asynchronous action synchronously (blocks until the continuation has /// been invoked). /// </summary> /// <param name="action">The action.</param> /// <remarks> /// Using this method is not recommended because it will block the calling thread. /// </remarks> public static void RunSynchronously(AsynchronousAction action) { RunSynchronously(null, action); }
/// <summary> /// Iterates over all items in the given collection and runs the specified action /// in parallel (each action executes on a thread from thread pool). /// </summary> /// <typeparam name="T">Type of each item.</typeparam> /// <param name="values">The items to iterate.</param> /// <param name="asyncContinuation">The asynchronous continuation to invoke once all items /// have been iterated.</param> /// <param name="action">The action to invoke for each item.</param> public static void ForEachItemInParallel <T>(IEnumerable <T> values, AsyncContinuation asyncContinuation, AsynchronousAction <T> action) { action = ExceptionGuard(action); var items = new List <T>(values); int remaining = items.Count; var exceptions = new List <Exception>(); InternalLogger.Trace("ForEachItemInParallel() {0} items", items.Count); if (remaining == 0) { asyncContinuation(null); return; } AsyncContinuation continuation = ex => { InternalLogger.Trace("Continuation invoked: {0}", ex); if (ex != null) { lock (exceptions) { exceptions.Add(ex); } } var r = Interlocked.Decrement(ref remaining); InternalLogger.Trace("Parallel task completed. {0} items remaining", r); if (r == 0) { asyncContinuation(GetCombinedException(exceptions)); } }; foreach (T item in items) { T itemCopy = item; StartAsyncTask(s => { try { action(itemCopy, PreventMultipleCalls(continuation)); } catch (Exception ex) { InternalLogger.Error(ex, "ForEachItemInParallel - Unhandled Exception"); if (ex.MustBeRethrownImmediately()) { throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior) } } }, null); } }
/// <summary> /// Modifies the continuation by pre-pending given action to execute just before it. /// </summary> /// <param name="asyncContinuation">The async continuation.</param> /// <param name="action">The action to pre-pend.</param> /// <returns>Continuation which will execute the given action before forwarding to the actual continuation.</returns> public static AsyncContinuation PrecededBy(AsyncContinuation asyncContinuation, AsynchronousAction action) { action = ExceptionGuard(action); AsyncContinuation continuation = ex => { if (ex != null) { // if got exception from from original invocation, don't execute action asyncContinuation(ex); return; } // call the action and continue action(PreventMultipleCalls(asyncContinuation)); }; return(continuation); }
/// <summary> /// Repeats the specified asynchronous action multiple times and invokes asynchronous continuation at the end. /// </summary> /// <param name="repeatCount">The repeat count.</param> /// <param name="asyncContinuation">The asynchronous continuation to invoke at the end.</param> /// <param name="action">The action to invoke.</param> public static void Repeat(int repeatCount, AsyncContinuation asyncContinuation, AsynchronousAction action) { action = ExceptionGuard(action); AsyncContinuation invokeNext = null; int remaining = repeatCount; invokeNext = ex => { if (ex != null) { asyncContinuation(ex); return; } if (remaining-- <= 0) { asyncContinuation(null); return; } action(PreventMultipleCalls(invokeNext)); }; invokeNext(null); }
/// <summary> /// Iterates over all items in the given collection and runs the specified action /// in parallel (each action executes on a thread from thread pool). /// </summary> /// <typeparam name="T">Type of each item.</typeparam> /// <param name="values">The items to iterate.</param> /// <param name="asyncContinuation">The asynchronous continuation to invoke once all items /// have been iterated.</param> /// <param name="action">The action to invoke for each item.</param> public static void ForEachItemInParallel <T>(IEnumerable <T> values, AsyncContinuation asyncContinuation, AsynchronousAction <T> action) { ForEachItemInParallel(null, values, asyncContinuation, action); }
/// <summary> /// Repeats the specified asynchronous action multiple times and invokes asynchronous continuation at the end. /// </summary> /// <param name="repeatCount">The repeat count.</param> /// <param name="asyncContinuation">The asynchronous continuation to invoke at the end.</param> /// <param name="action">The action to invoke.</param> public static void Repeat(int repeatCount, AsyncContinuation asyncContinuation, AsynchronousAction action) { Repeat(null, repeatCount, asyncContinuation, action); }
/// <summary> /// Iterates over all items in the given collection and runs the specified action /// in parallel (each action executes on a thread from thread pool). /// </summary> /// <typeparam name="T">Type of each item.</typeparam> /// <param name="values">The items to iterate.</param> /// <param name="asyncContinuation"> /// The asynchronous continuation to invoke once all items /// have been iterated. /// </param> /// <param name="action">The action to invoke for each item.</param> public static void ForEachItemInParallel <T>(IEnumerable <T> values, AsyncContinuation asyncContinuation, AsynchronousAction <T> action) { action = ExceptionGuard(action); var items = new List <T>(values); var remaining = items.Count; var exceptions = new List <Exception>(); InternalLogger.Trace("ForEachItemInParallel() {0} items", items.Count); if (remaining == 0) { asyncContinuation(null); return; } AsyncContinuation continuation = ex => { InternalLogger.Trace("Continuation invoked: {0}", ex); int r; if (ex != null) { lock (exceptions) { exceptions.Add(ex); } } r = Interlocked.Decrement(ref remaining); InternalLogger.Trace("Parallel task completed. {0} items remaining", r); if (r == 0) { asyncContinuation(GetCombinedException(exceptions)); } }; foreach (var item in items) { var itemCopy = item; ThreadPool.QueueUserWorkItem(s => action(itemCopy, PreventMultipleCalls(continuation))); } }