/* expected exit code: 255 */ static void Main (string[] args) { if (Environment.GetEnvironmentVariable ("TEST_UNHANDLED_EXCEPTION_HANDLER") != null) AppDomain.CurrentDomain.UnhandledException += (s, e) => {}; ManualResetEvent mre = new ManualResetEvent (false); var a = new Action (() => { try { throw new CustomException (); } finally { mre.Set (); } }); var ares = a.BeginInvoke (null, null); if (!mre.WaitOne (5000)) Environment.Exit (2); try { a.EndInvoke (ares); Environment.Exit (4); } catch (CustomException) { /* expected behaviour */ Environment.Exit (255); } catch (Exception ex) { Console.WriteLine (ex); Environment.Exit (3); } Environment.Exit (5); }
private static void CheckoutFileIfRequired(_DTE dte, String fileName) { _checkOutAction = (String fn) => dte.SourceControl.CheckOutItem(fn); var sc = dte.SourceControl; if (sc != null && sc.IsItemUnderSCC(fileName) && !sc.IsItemCheckedOut(fileName)) _checkOutAction.EndInvoke(_checkOutAction.BeginInvoke(fileName, null, null)); }
public void BatchSave_Info(List<Entity.CurrencyInfo> values) { var action = new Action(() => { service.BatchSave_Info(values); }); action.BeginInvoke((ar) => { action.EndInvoke(ar); ServerInstrumentation.Current.Queue(-1); }, action); }
public void Start(IWin32Window owner, int fileCount, Action action) { progressBar.Maximum = fileCount; Show(owner); action.BeginInvoke( ar => { action.EndInvoke(ar); Action hideAction = EndProgress; Invoke(hideAction); }, null); }
public static bool AsyncCallAndWait(Action action) { IAsyncResult result = action.BeginInvoke(null, null); try { action.EndInvoke(result); } catch (Exception) { return false; } return true; }
public void Restore(string cloudName) { Action action = new Action(() => { if (DownloadFromCloud(cloudName)) { MergeDB(cloudName); MessageBox.Show("云还原成功"); } }); action.BeginInvoke((ar) => action.EndInvoke(ar), action); }
private bool Wait(Action action, int timeout) { var handle = action.BeginInvoke(null, null); if (handle.AsyncWaitHandle.WaitOne(timeout)) { action.EndInvoke(handle); return false; } return true; }
public bool RunSync(Action<CancelEventArgs> action, TimeSpan maxRuntime) { if (maxRuntime.TotalMilliseconds <= 0) { throw new ArgumentOutOfRangeException("maxRuntime"); } CancelEventArgs args = new CancelEventArgs(false); IAsyncResult functionResult = action.BeginInvoke(args, null, null); WaitHandle waitHandle = functionResult.AsyncWaitHandle; if (!waitHandle.WaitOne(maxRuntime)) { args.Cancel = true; // flag to worker that it should cancel! ThreadPool.UnsafeRegisterWaitForSingleObject(waitHandle, (state, timedOut) => action.EndInvoke(functionResult), null, -1, true); return false; } action.EndInvoke(functionResult); return true; }
public void Bakcup(string cloudName) { string dbPath = DBHelper.GetDBPath(DBHelper.DBName); Action action = new Action(() => { if (OSSHelper.UploadFile(dbPath, cloudName)) { MessageBox.Show("云备份成功"); } }); action.BeginInvoke((ar) => action.EndInvoke(ar), action); }
/// <summary> /// オペレーションスケジュールを登録します。<para /> /// 実行可能な場合はすぐに実行します。 /// </summary> /// <param name="operation">オペレーション(サブスレッドで実行されます)</param> /// <param name="condition">発動条件、またはNULL</param> internal static void RegisterSchedule(Action operation, Func<bool> condition) { if (condition == null || condition()) { operation.BeginInvoke((iar) => operation.EndInvoke(iar), null); } else { lock (queuelock) { queuings.Add(new QueuedOperation(operation, condition)); } } }
public static void ExportMySQL() { if (!CMOptions.ModuleEnabled || !CMOptions.MySQLEnabled || !CMOptions.MySQLInfo.IsValid()) { if (_Connection != null) { _Connection.Dispose(); _Connection = null; } return; } if (_Connection != null && !_Connection.IsDisposed) { return; } CMOptions.ToConsole("Updating MySQL database..."); VitaNexCore.TryCatch( () => { _Connection = new MySQLConnection(CMOptions.MySQLInfo); _Connection.ConnectAsync(0, true,() => { var a = new Action(UpdateMySQL); a.BeginInvoke( r => { a.EndInvoke(r); UpdateMySQL(); }, null); }); }, x => { if (_Connection != null) { _Connection.Dispose(); _Connection = null; } CMOptions.ToConsole(x); }); }
public static void SaveAsync(IStorableContent content, string filename, bool compressed, Action<IStorableContent, Exception> savingCompletedCallback) { if (instance == null) throw new InvalidOperationException("ContentManager is not initialized."); var action = new Action<IStorableContent, string, bool>(instance.SaveContent); action.BeginInvoke(content, filename, compressed, delegate(IAsyncResult result) { Exception error = null; try { action.EndInvoke(result); content.Filename = filename; } catch (Exception ex) { error = ex; } savingCompletedCallback(content, error); }, null); }
public void StopTracing() { refCount--; if (refCount != 0) { return; } stopProcessing = true; NativeMethods.CloseTrace(this.traceHandle); traceHandle = 0; processEventsDelegate.EndInvoke(asyncResult); StopTrace(); Marshal.FreeCoTaskMem(this.traceProperties); this.traceProperties = IntPtr.Zero; }
public void Processor(bool async = false) { var items = this.Reset(); if (async) { Processor(items); } else { var action = new Action(() => Processor(items)); action.BeginInvoke((ar) => { action.EndInvoke(ar); }, action); } }
public void Processor(bool async = false) { var items = this.Reset(); if (async) { Processor(items); } else { var action = new Action(() => Processor(items)); action.BeginInvoke((ar) => { action.EndInvoke(ar); ServerInstrumentation.Current.Queue(-1); }, action); } }
public static void Do(Action<ManualResetEvent> callback, Action action, int timeout) { var evt = new ManualResetEvent(false); IAsyncResult resultAction = null; IAsyncResult resultCallback = callback.BeginInvoke(evt, ar => resultAction = action.BeginInvoke(ar2 => evt.Set(), null), null); if (evt.WaitOne(timeout)) { callback.EndInvoke(resultCallback); action.EndInvoke(resultAction); } else { throw new TimeoutException(); } }
static void DoTest2 () { mre.Reset (); var a = new Action (() => { try { throw new CustomException (); } finally { mre.Set (); } }); var ares = a.BeginInvoke (null, null); if (!mre.WaitOne (5000)) Environment.Exit (2); try { a.EndInvoke (ares); throw new Exception (); } catch (CustomException) { } catch (Exception) { Environment.Exit (3); } }
public bool Resume(Bookmark bookmark, FileInfo source, FileInfo destination, Statements.FileCopyOptions options, int stepIncrement) { var context = new CopyFileContext(stepIncrement) { Instance = this, Bookmark = bookmark, Action = CopyFileAction.Continue }; if (contexts.TryAdd(bookmark.Name, context)) { var action = new Action(() => ExecuteCopyFile(context, source, destination, options)); action.BeginInvoke((a) => { try { action.EndInvoke(a); } catch (Exception ex) { ((CopyFileContext)a.AsyncState).Exception = ex; } finally { ((CopyFileContext)a.AsyncState).NotifyCompletion(); } }, context); return true; } return false; }
/* expected exit code: 0 */ static void Main (string[] args) { ManualResetEvent mre = new ManualResetEvent (false); var a = new Action (() => { try { throw new CustomException (); } finally { mre.Set (); } }); var ares = a.BeginInvoke (null, null); if (!mre.WaitOne (5000)) Environment.Exit (2); try { a.EndInvoke (ares); Environment.Exit (4); } catch (CustomException) { } catch (Exception ex) { Console.WriteLine (ex); Environment.Exit (3); } Environment.Exit (0); }
/// <summary> /// 带超时时间的方法调用 /// </summary> /// <param name="action"></param> /// <param name="timeoutMilliseconds"></param> void CallWithTimeout(System.Action action, int timeoutMilliseconds) { try { if (action == null) { return; } Thread threadToKill = null; System.Action wrappedAction = () => { threadToKill = Thread.CurrentThread; action(); }; IAsyncResult result = wrappedAction.BeginInvoke(null, null); if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds)) { wrappedAction.EndInvoke(result); } else { threadToKill.Abort(); throw new TimeoutException(); } } catch (TimeoutException) { //action.Method.Name获取方法名,匿名时采用<父函数名>b_0_0 InternalLogger.Log.Error(String.Format("调用{0}方法超过{1}毫秒,请检查与设备通信链路。", action.Method.Name, timeoutMilliseconds)); } catch (Exception ex) { InternalLogger.Log.Error("带超时时间的方法调用出错:" + ex.Message); } }
private void StartRound(bool isByOss = false) { if (!isStarted) { return; } int roundId = GetRoundId(); string newRoundID = GetLatestRoundId(); if (!string.IsNullOrEmpty(newRoundID) && roundId < int.Parse(newRoundID)) { lblState.Text = string.Format("当前:{0}已经过期,新一轮为:{1}", roundId, newRoundID); txtRoundId.Text = newRoundID; txtRoundId.ForeColor = Color.Red; return; } int[] values = ucNum28.GetValues(); if (roundId <= 0 || values == null) { return; } int currentToal = values.Sum(); GetCurrentBeans(); string total = lblBeans.Text.Replace(",", ""); int totalSum = 0; int.TryParse(total, out totalSum); if (!string.IsNullOrEmpty(total) && currentToal >= totalSum) { lblState.Text = "当前下注U豆大于所拥有U豆,本期下注被取消"; return; } if (currentToal >= AppSetting.MaxLimit) { lblState.Text = "当前下注大于最大限止,本期下注被取消"; return; } lblState.Text = "开始下注"; Action action = new Action(() => { bool isUpload = !isByOss && this.isSupportOssRule; if (isUpload) { RuleFileHelper.SaveSpeed28Rule(roundId, values); } ResultCode code = speed28.StartNewRound(roundId, values); if (isUpload && code == ResultCode.Succeed) OSSHelper.UploadRuleToOSS(); }); action.BeginInvoke((ar) => { action.EndInvoke(ar); }, action); }
public IAsyncResult Stop() { Action action = new Action(() => { if (VlcMediaPlayer.Media == null) return; VlcMediaPlayer.SetVideoDecodeCallback(null, null, null, IntPtr.Zero); VlcMediaPlayer.SetVideoFormatCallback(null, null); if (VlcMediaPlayer.State == MediaState.Playing) { _stopping = true; VlcMediaPlayer.Pause(); } while (_stopping) { } }); return action.BeginInvoke((aresult) => { VlcMediaPlayer.Stop(); if (_context != null) _context.Dispose(); _context = null; Dispatcher.BeginInvoke(new Action(() => VideoSource = null)); action.EndInvoke(aresult); }, null); }
void Metadata_HostsEvent(object sender, HostsEventArgs e) { if (sender == this) return; if (_activeConnection.Value == null) return; Action<object> act = new Action<object>((_) => SetupControlConnection()); if (e.What == HostsEventArgs.Kind.Down) { if (e.IPAddress.Equals(_activeConnection.Value.GetHostAdress())) act.BeginInvoke(null, (ar) => { act.EndInvoke(ar); }, null); } else if (e.What == HostsEventArgs.Kind.Up) { if (_isDiconnected) act.BeginInvoke(null, (ar) => { act.EndInvoke(ar); }, null); } }
private void conn_CassandraEvent(object sender, CassandraEventArgs e) { var act = new Action<object>((_) => { if (e is TopologyChangeEventArgs) { var tce = e as TopologyChangeEventArgs; if (tce.What == TopologyChangeEventArgs.Reason.NewNode) { SetupControlConnection(true); _cluster.Metadata.AddHost(tce.Address); return; } else if (tce.What == TopologyChangeEventArgs.Reason.RemovedNode) { _cluster.Metadata.RemoveHost(tce.Address); SetupControlConnection(_activeConnection.Value == null ? false : !tce.Address.Equals(_activeConnection.Value.GetHostAdress())); return; } } else if (e is StatusChangeEventArgs) { var sce = e as StatusChangeEventArgs; if (sce.What == StatusChangeEventArgs.Reason.Up) { _cluster.Metadata.BringUpHost(sce.Address, this); return; } else if (sce.What == StatusChangeEventArgs.Reason.Down) { _cluster.Metadata.SetDownHost(sce.Address, this); return; } } else if (e is SchemaChangeEventArgs) { var ssc = e as SchemaChangeEventArgs; if (ssc.What == SchemaChangeEventArgs.Reason.Created) { SubmitSchemaRefresh(string.IsNullOrEmpty(ssc.Keyspace) ? null : ssc.Keyspace, null); _cluster.Metadata.FireSchemaChangedEvent(SchemaChangedEventArgs.Kind.Created, string.IsNullOrEmpty(ssc.Keyspace) ? null : ssc.Keyspace, ssc.Table); return; } else if (ssc.What == SchemaChangeEventArgs.Reason.Dropped) { SubmitSchemaRefresh(string.IsNullOrEmpty(ssc.Keyspace) ? null : ssc.Keyspace, null); _cluster.Metadata.FireSchemaChangedEvent(SchemaChangedEventArgs.Kind.Dropped, string.IsNullOrEmpty(ssc.Keyspace) ? null : ssc.Keyspace, ssc.Table); return; } else if (ssc.What == SchemaChangeEventArgs.Reason.Updated) { SubmitSchemaRefresh(ssc.Keyspace, string.IsNullOrEmpty(ssc.Table) ? null : ssc.Table); _cluster.Metadata.FireSchemaChangedEvent(SchemaChangedEventArgs.Kind.Updated, string.IsNullOrEmpty(ssc.Keyspace) ? null : ssc.Keyspace, ssc.Table); return; } } var ex = new DriverInternalError("Unknown Event"); _logger.Error(ex); throw ex; }); act.BeginInvoke(null, (ar) => { act.EndInvoke(ar); }, null); }
/// <summary> /// Finalizes data loading and returns the result argument based on the specified synchronization called by a BeginLoad function. /// </summary> /// <param name="result">System.IAsyncResult generated from a BeginLoad method call</param> /// <returns>Development.Materia.Database.DataBinderLoadingEventArgs generated from the DataBinding loading routines.</returns> public DataBinderLoadingEventArgs EndLoad(IAsyncResult result) { DataBinderLoadingEventArgs _args = null; if (_delegatetable.ContainsKey(result)) { Func<DataBinderLoadingEventArgs> _delegate = (Func<DataBinderLoadingEventArgs>)_delegatetable[result]; _args = _delegate.EndInvoke(result); _delegatetable.Remove(result); if (!_args.Cancel) { Control.CheckForIllegalCrossThreadCalls = false; Action _binddelegate = new Action(Bind); IAsyncResult _result = _binddelegate.BeginInvoke(null, _binddelegate); while (!_result.IsCompleted && !_binder.CancelRunningProcess) { Materia.RaiseEvent(_binder, "DataLoading", new EventArgs()); Thread.Sleep(1); Application.DoEvents(); } if (_binder.CancelRunningProcess) { if (_result.IsCompleted) { try { _result = null; } catch { } } return null; } _binddelegate.EndInvoke(_result); Materia.RaiseEvent(_binder, "AfterBindingDataLoad", _args); } else return null; } return _args; }
private void SaveButton_Click(object sender, EventArgs e) { object _button = sender; if (_button == null) return; bool _enabled = Materia.GetPropertyValue<bool>(_button, "Enabled", true); if (!_enabled) return; _saving = false; GridFinishEdit(); DataBinderValidationEventArgs _args = Validate(); if (_args != null) { if (!_args.Valid) { if (_args.Control != null) { if (_args.Control.GetType().Name.ToLower().Contains("C1FlexGrid".ToLower()) || _args.Control.GetType().BaseType.Name.ToLower().Contains("C1FlexGrid".ToLower())) { if (!String.IsNullOrEmpty(_args.Notification.RLTrim())) { SetControlFocus((Control) _args.Control); MessageBox.Show(_args.Notification, "Entry Validation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); bool _allowediting = true; try { _allowediting = Materia.GetPropertyValue<bool>(_args.Control, "AllowEditing", true); } catch { } if (_allowediting) { int _row = -1; int _col = -1; try { _row = Materia.GetPropertyValue<int>(_args.Control, "Row", -1); } catch { } try { _col = Materia.GetPropertyValue<int>(_args.Control, "Col", -1); } catch { } if (_row > -1 && _col > -1) { try { Materia.InvokeMethod(_args.Control, "StartEditing", new object[] { _row, _col }); } catch { } } } } return; } else return; } else return; } else { if (_args.Cancel) return; } _enabled = Materia.GetPropertyValue<bool>(_button, "Enabled", true); try { Materia.SetPropertyValue(_button, "Enabled", false); } catch { } CancelRunningProcess = false; _saving = true; Action _valuesetdelegate = new Action(SetFieldValues); IAsyncResult _valuesetresult = _valuesetdelegate.BeginInvoke(null, _valuesetdelegate); while (!_valuesetresult.IsCompleted && !CancelRunningProcess) { OnDataGathering(new EventArgs()); Thread.Sleep(1); Application.DoEvents(); } if (CancelRunningProcess) { if (!_valuesetresult.IsCompleted) { try { _valuesetresult = null; } catch { } } try { Materia.SetPropertyValue(_button, "Enabled", _enabled); } catch { } Materia.RefreshAndManageCurrentProcess(); _saving = false; return; } _valuesetdelegate.EndInvoke(_valuesetresult); Action _fksetdelegate = new Action(SetForeignKeys); IAsyncResult _fksetresult = _fksetdelegate.BeginInvoke(null, _fksetdelegate); while (!_fksetresult.IsCompleted && !CancelRunningProcess) { OnDataGathering(new EventArgs()); Thread.Sleep(1); Application.DoEvents(); } if (CancelRunningProcess) { if (!_fksetresult.IsCompleted) { try { _fksetresult = null; } catch { } } try { Materia.SetPropertyValue(_button, "Enabled", _enabled); } catch { } Materia.RefreshAndManageCurrentProcess(); _saving = false; return; } _fksetdelegate.EndInvoke(_fksetresult); Func<string> _sqlgetdelegate = new Func<string>(Binding.GetUpdateStatements); IAsyncResult _sqlgetresult = _sqlgetdelegate.BeginInvoke(null, _sqlgetdelegate); while (!_sqlgetresult.IsCompleted && !CancelRunningProcess) { OnDataGathering(new EventArgs()); Thread.Sleep(1); Application.DoEvents(); } if (CancelRunningProcess) { if (!_sqlgetresult.IsCompleted) { try { _sqlgetresult = null; } catch { } } try { Materia.SetPropertyValue(_button, "Enabled", _enabled); } catch { } Materia.RefreshAndManageCurrentProcess(); _saving = false; return; } string _sql = _sqlgetdelegate.EndInvoke(_sqlgetresult); try { Materia.SetPropertyValue(_button, "Enabled", _enabled); } catch { } DataBinderSavingEventArgs _saveargs = new DataBinderSavingEventArgs(_sql); OnBeforeDataSave(_saveargs); AcceptUpdates(); if (!_saveargs.Cancel) { try { Materia.SetPropertyValue(_button, "Enabled", false); } catch { } _sql = ""; Func<string> _sqlgetfinaldelegate = new Func<string>(Binding.GetUpdateStatements); IAsyncResult _sqlgetfinalresult = _sqlgetfinaldelegate.BeginInvoke(null, _sqlgetfinaldelegate); while (!_sqlgetfinalresult.IsCompleted && !CancelRunningProcess) { OnDataGathering(new EventArgs()); Thread.Sleep(1); Application.DoEvents(); } if (CancelRunningProcess) { if (_sqlgetfinalresult != null) { try { _sqlgetfinalresult = null; } catch { } } try { Materia.SetPropertyValue(_button, "Enabled", _enabled); } catch { } Materia.RefreshAndManageCurrentProcess(); _saving = false; return; } string _query = _sqlgetfinaldelegate.EndInvoke(_sqlgetfinalresult); if (WithBlobDataSource()) { if (!String.IsNullOrEmpty(_query.RLTrim())) { if (!_query.RLTrim().ToLower().StartsWith("set global max_allowed_packet")) _sql = "SET GLOBAL max_allowed_packet = (1024 * 1204) * " + MySql.MaxAllowedPacket.ToString() + ";"; } } _sql += ((!String.IsNullOrEmpty(_sql.RLTrim())) ? "\n" : "") + _query; if (String.IsNullOrEmpty(_sql.RLTrim())) { try { Materia.SetPropertyValue(_button, "Enabled", _enabled); } catch { } Materia.RefreshAndManageCurrentProcess(); _saving = false; return; } _saveargs.CommandText = _sql; OnDataSaveExecuting(_saveargs); if (_saveargs.Cancel) { try { Materia.SetPropertyValue(_button, "Enabled", _enabled); } catch { } Materia.RefreshAndManageCurrentProcess(); _saving = false; return; } _sql = _saveargs.CommandText; IAsyncResult _saveresult = Que.BeginExecution(Connection, _sql, CommandExecution.ExecuteNonQuery); while (!_saveresult.IsCompleted && !CancelRunningProcess) { OnDataSaving(new EventArgs()); Thread.Sleep(1); Application.DoEvents(); } if (CancelRunningProcess) { if (!_saveresult.IsCompleted) { try { _saveresult = null; } catch { } } try { Materia.SetPropertyValue(_button, "Enabled", _enabled); } catch { } Materia.RefreshAndManageCurrentProcess(); _saving = false; return; } QueResult _result = Que.EndExecution(_saveresult); _saveargs = null; if (_result == null) { try { Materia.SetPropertyValue(_button, "Enabled", _enabled); } catch { } Materia.RefreshAndManageCurrentProcess(); _saving = false; return; } else { if (!String.IsNullOrEmpty(_result.Error.RLTrim())) _saveargs = new DataBinderSavingEventArgs(_sql, _result.Error); else _saveargs = new DataBinderSavingEventArgs(_sql, _result.RowsAffected); if (!String.IsNullOrEmpty(_result.Error.RLTrim())) _saveargs.ErrorNotification = "An error occured while trying to save the changes and updates to the current record(s). Please try again and\n/ or report this issue to the system administrator."; else { Action _updatedelegate = new Action(Update); IAsyncResult _updateresult = _updatedelegate.BeginInvoke(null, _updatedelegate); while (!_updateresult.IsCompleted) { OnDataLoading(new EventArgs()); Thread.Sleep(1); Application.DoEvents(); } _updatedelegate.EndInvoke(_updateresult); } try { Materia.SetPropertyValue(_button, "Enabled", _enabled); } catch { } Materia.RefreshAndManageCurrentProcess(); _saving = false; AcceptUpdates(); OnAfterDataSave(_saveargs); if (!String.IsNullOrEmpty(_saveargs.Error.RLTrim()) && !String.IsNullOrEmpty(_saveargs.ErrorNotification.RLTrim())) MessageBox.Show(_saveargs.ErrorNotification, "Record Update Failed", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); if (!_saveargs.Cancel) { AcceptAllChanges(); _haveupdates = false; Form _form = null; try { _form = (Form)ContainerControl; } catch { _form = null; } if (_form != null) { if (_form.Text.RLTrim().EndsWith("*")) _form.Text = _form.Text.Replace("*", ""); } } } } } }
private void refreshButton_Click(object sender, EventArgs e) { var invoker = new Action<RefreshableJob>(HiveClient.LoadJob); invoker.BeginInvoke(Content, (ar) => { try { invoker.EndInvoke(ar); } catch (Exception ex) { ThreadPool.QueueUserWorkItem(delegate(object exception) { ErrorHandling.ShowErrorDialog(this, (Exception)exception); }, ex); } }, null); }
public object Invoke(Delegate method, object[] args) { sawInvoke = true; action = () => method.DynamicInvoke(args); action.EndInvoke(action.BeginInvoke(null, null)); return null; }
private void btnGetHistory_Click(object sender, EventArgs e) { Action action = new Action(() => { //http://game.juxiangyou.com/speed28/index.php?p=50 int pages = 0; if (!int.TryParse(txtPages.Text, out pages)) { return; } if (pages > 50) { pages = 50; } for (int i = 0; i <= pages; i++) { string table = speed28.GetHistoryByPage(i); if (!string.IsNullOrEmpty(table)) { IList<HistoryInfo> list = parser.GetRowsFromHtml(table); list = list.OrderByDescending(item => item.RoundId).ToList(); dbHelper.InsertHistory(list); Debug.WriteLine(string.Format("/--- current history page:{0} queryed ---/", i)); string progress = string.Format("当前加载完:{0}页,共:{1}条记录", i, list.Count); this.BeginInvoke(new Action(() => { lblHistoryLog.Text = progress; })); } } this.BeginInvoke(new Action(() => { lblHistoryLog.Text = string.Format("完成"); })); }); action.BeginInvoke((ar) => action.EndInvoke(ar), action); }
void ReadOutputs(Process proc, string freezemsg, Action<string> stdOutRead, Action<string> stdErrRead) { proc.Start(); object syncObj = new object(); var readThread = new Action<StreamReader, Action<string>>((sr, action) => { Properties.Settings.SetCurrentLanguage(); try { while (!sr.EndOfStream) { if (abort) return; var str = sr.ReadLine(); if (str != null) { lock (syncObj) { action(str); } } } } catch (System.Threading.ThreadAbortException) { return; } }); var ReadStdOutThread = readThread.BeginInvoke(proc.StandardOutput, stdOutRead, null, null); var ReadStdErrThread = readThread.BeginInvoke(proc.StandardError, stdErrRead, null, null); while (true) { proc.WaitForExit(Properties.Settings.Default.timeOut <= 0 ? 100 : Properties.Settings.Default.timeOut); if (proc.HasExited) { break; } else { bool kill = false; if (Properties.Settings.Default.timeOut > 0) { if (Properties.Settings.Default.batchMode == Properties.Settings.BatchMode.Default && controller_ != null) { // プロセスからの読み取りを一時中断するためのlock。 // でないと特にCUI時にメッセージが混ざってわけがわからなくなる。 lock (syncObj) { kill = !controller_.askYesorNo(String.Format(Properties.Resources.FREEZMSG, freezemsg)); } } else kill = (Properties.Settings.Default.batchMode == Properties.Settings.BatchMode.Stop); } if (kill || abort) { //proc.Kill(); KillChildProcesses(proc); if (!ReadStdOutThread.IsCompleted || !ReadStdErrThread.IsCompleted) { System.Threading.Thread.Sleep(500); abort = true; } if (controller_ != null) controller_.appendOutput(Properties.Resources.STOPCONVERTMSG + "\n"); readThread.EndInvoke(ReadStdOutThread); readThread.EndInvoke(ReadStdErrThread); throw new System.TimeoutException(); } else continue; } } // 残っているかもしれないのを読む。 while (!ReadStdOutThread.IsCompleted || !ReadStdErrThread.IsCompleted) { System.Threading.Thread.Sleep(300); } readThread.EndInvoke(ReadStdOutThread); readThread.EndInvoke(ReadStdErrThread); if (controller_ != null) controller_.appendOutput("\n"); if (abort) throw new System.TimeoutException(); }
/// <summary> /// Starts a message pump running on the current thread and performs the /// specified action in another thread. The action can asynchronously communicate back to the /// cmdlet using <see cref="PostMessage" /> on the current thread. /// </summary> /// <param name="action">The action to perform.</param> public void RunWithMessagePump(Action action) { bool loopInitialized = false; try { lock (this) { if (pendingBlocks != null) throw new InvalidOperationException("Already have a message pump."); pendingBlocks = new Queue<Action>(); loopInitialized = true; } IAsyncResult result = action.BeginInvoke(QuitMessagePump, action); RunMessagePumpUntilQuit(); action.EndInvoke(result); } finally { if (loopInitialized) { lock (this) pendingBlocks = null; } } }
public void WriteBlocksWhileReadIsInEffect() { _routes.MapRoute("foo", "{controller}"); var publisher = _container.Resolve<IRoutePublisher>(); var readLock = _routes.GetReadLock(); string where = "init"; var action = new Action(() => { where = "before"; publisher.Publish(new[] { Desc("barname", "bar"), Desc("quuxname", "quux") }); where = "after"; }); Assert.That(where, Is.EqualTo("init")); var asyncResult = action.BeginInvoke(null, null); Thread.Sleep(75); Assert.That(where, Is.EqualTo("before")); readLock.Dispose(); Thread.Sleep(75); Assert.That(where, Is.EqualTo("after")); action.EndInvoke(asyncResult); }