private void bt4_Click(object sender, EventArgs e) { b = new StringBuilder(); ThreadStart ts = new ThreadStart(t1Start); IAsyncResult r1 = ts.BeginInvoke(null, null); IAsyncResult r2 = ts.BeginInvoke(null, null); ts.EndInvoke(r1); ts.EndInvoke(r2); tbOut.Text = b.ToString(); }
/** * Runs the specified process */ public void Run(String fileName, String arguments) { this.isRunning = true; this.process = new Process(); this.process.StartInfo.UseShellExecute = false; this.process.StartInfo.RedirectStandardOutput = true; this.process.StartInfo.RedirectStandardError = true; this.process.StartInfo.RedirectStandardInput = true; this.process.StartInfo.CreateNoWindow = true; this.process.StartInfo.FileName = fileName; this.process.StartInfo.Arguments = arguments; this.process.StartInfo.WorkingDirectory = Environment.CurrentDirectory; this.process.Start(); this.outputReader = process.StandardOutput; this.errorReader = process.StandardError; // We need to wait for all 3 of our threadpool operations to finish (processexit, readoutput, readerror) this.tasksFinished = 0; // Do our waiting on the threadpool ThreadStart waitForExitDel = new ThreadStart(process.WaitForExit); waitForExitDel.BeginInvoke(new AsyncCallback(TaskFinished), null); // Also read outputs on the threadpool ThreadStart readOutputDel = new ThreadStart(this.ReadOutput); ThreadStart readErrorDel = new ThreadStart(this.ReadError); readOutputDel.BeginInvoke(new AsyncCallback(this.TaskFinished), null); readErrorDel.BeginInvoke(new AsyncCallback(this.TaskFinished), null); }
private void AcceptFinished(IAsyncResult result) { if (_listener == null) { return; } try { Socket s = _listener.EndAccept(result); var processor = new HttpProcessor(s, this); var DoWork = new ThreadStart(delegate { processor.Process(); }); DoWork.BeginInvoke(null, null); } catch { } finally { // start listening for the next one if (_listener != null) { try { _listener.BeginAccept(AcceptFinished, null); } catch { } } } }
private void TimerThreadCallback(TimerCallback timerCallback) { ThreadStart threadStart = new ThreadStart(() => { Thread.Sleep(_Period); lock (_Lock) { if (_IsRunning) {// we have to check whether we are still running, otherwise we might end up sending this signal for a new thread start Monitor.Pulse(_Lock); } } }); lock (_Lock) { while (_IsRunning) { if (_PreciseTimerCallbackMode == PreciseTimerCallbackMode.Synchronized) { timerCallback.Invoke(null); } else { timerCallback.BeginInvoke(null, null, null); } threadStart.BeginInvoke(null, null); Monitor.Wait(_Lock); } } }
public void Run(String fileName, String arguments, Boolean shellCommand) { if (isRunning) throw new Exception("This ProcessRunner is already running a process."); if (!shellCommand && !File.Exists(fileName)) throw new FileNotFoundException("The program '" + fileName + "' was not found.", fileName); isRunning = true; process = new Process(); process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = RedirectInput; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.StandardOutputEncoding = Encoding.Default; process.StartInfo.StandardErrorEncoding = Encoding.Default; process.StartInfo.CreateNoWindow = true; process.StartInfo.FileName = fileName; process.StartInfo.Arguments = arguments; process.StartInfo.WorkingDirectory = WorkingDirectory ?? PluginBase.MainForm.WorkingDirectory; process.Start(); outputReader = process.StandardOutput; errorReader = process.StandardError; // we need to wait for all 3 threadpool operations // to finish (processexit, readoutput, readerror) tasksFinished = 0; ThreadStart waitForExitDel = new ThreadStart(process.WaitForExit); waitForExitDel.BeginInvoke(new AsyncCallback(TaskFinished), null); ThreadStart readOutputDel = new ThreadStart(ReadOutput); ThreadStart readErrorDel = new ThreadStart(ReadError); readOutputDel.BeginInvoke(new AsyncCallback(TaskFinished), null); readErrorDel.BeginInvoke(new AsyncCallback(TaskFinished), null); }
private void Form1_Load(object sender, EventArgs e) { foreach (string name in names) { ToolStripMenuItem tsi = new ToolStripMenuItem(name); tsi.Click += ToolStripMenuItem_Click; contextMenuStrip1.Items.Add(tsi); } if (!File.Exists(strDownloadPath + "\\trainedImages.xml")) { return; } string xml = File.ReadAllText(strDownloadPath + "\\trainedImages.xml"); trainedFaces = (SeDes.ToObj(xml, trainedFaces) as List <trainedFace>); ThreadStart ts = new ThreadStart(fixFaces); progressBar1.Visible = true; IAsyncResult iar = ts.BeginInvoke((AsyncCallback) => { this.Invoke((MethodInvoker) delegate { progressBar1.Visible = false; }); }, null); }
public void Run(string fileName, string arguments) { if (isRunning) throw new Exception("This ProcessRunner is already running a process."); if (!File.Exists(fileName)) throw new FileNotFoundException("The program '"+fileName+"' was not found.",fileName); isRunning = true; process = new Process(); process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.CreateNoWindow = true; process.StartInfo.FileName = fileName; process.StartInfo.Arguments = arguments; process.StartInfo.WorkingDirectory = Environment.CurrentDirectory; process.Start(); outputReader = process.StandardOutput; errorReader = process.StandardError; // we need to wait for all 3 of our threadpool operations to finish // (processexit, readoutput, readerror) tasksFinished = 0; // do our waiting on the threadpool ThreadStart waitForExitDel = new ThreadStart(process.WaitForExit); waitForExitDel.BeginInvoke(new AsyncCallback(TaskFinished),null); // also read outputs on the threadpool ThreadStart readOutputDel = new ThreadStart(ReadOutput); ThreadStart readErrorDel = new ThreadStart(ReadError); readOutputDel.BeginInvoke(new AsyncCallback(TaskFinished),null); readErrorDel.BeginInvoke(new AsyncCallback(TaskFinished),null); }
/// ///////////////////////////////////////////////////////////////// public static void StartThreadWithProgress(string strTitre, ThreadStart fonctionDemarrage, bool bWaitEnd) { if (m_form == null) { m_form = new CFormProgressTimos(); } m_form.ResetSegmentsProgression(); m_form.TopMost = true; m_form.BringToFront(); m_form.m_labelInfo.Text = strTitre; m_form.Show(); m_form.TopMost = false; m_form.Refresh(); if (bWaitEnd) { try { Thread th = new Thread(fonctionDemarrage); th.SetApartmentState(ApartmentState.STA); th.Start(); th.Join(); } catch {} try { m_form.Hide(); } catch { } } else { fonctionDemarrage.BeginInvoke(new AsyncCallback(m_form.OnEndProcess), null); } }
public void InitMessRabbitMQ() { try { var thread = new ThreadStart(() => { using (var rabRead = (Rabbitmq)MQFactory.CreateMessageQueue(MQFactory.MQType.RabbitMQ)) { rabRead.QueueIP = ConfigurationManager.AppSettings["QueueUrl"]; rabRead.QueueName = "MutualClass_Reward_Queue"; //队列名称 rabRead.VirtualHost = "5672"; //本地端口 外网端口15672 rabRead.ExchangeName = "RewardExchangeName"; //交换机 rabRead.UserName = "******"; rabRead.Password = "******"; rabRead.AutoAck = false; rabRead.onReceive += imq_onReceive; rabRead.RType = Rabbitmq.TypeName.Direct; rabRead.Init(); rabRead.SubscribeQueue(); rabRead.AddListening(); rabRead.ReceiveMQMessage(); // 结束时使用 rabRead.IsReceOver = true; } }); thread.BeginInvoke(null, null); } catch (Exception ex) { _Logger.Error($"有奖问卷 MutualClassRewardJob 订阅初始化异常", ex); } }
/** * Runs the specified process */ public void Run(String fileName, String arguments) { this.isRunning = true; this.process = new Process(); this.process.StartInfo.UseShellExecute = false; this.process.StartInfo.RedirectStandardOutput = true; this.process.StartInfo.RedirectStandardError = true; this.process.StartInfo.RedirectStandardInput = true; this.process.StartInfo.CreateNoWindow = true; this.process.StartInfo.FileName = fileName; this.process.StartInfo.Arguments = arguments; this.process.StartInfo.WorkingDirectory = Environment.CurrentDirectory; this.process.Start(); this.outputReader = process.StandardOutput; this.errorReader = process.StandardError; // We need to wait for all 3 of our threadpool operations to finish (processexit, readoutput, readerror) this.tasksFinished = 0; // Do our waiting on the threadpool ThreadStart waitForExitDel = new ThreadStart(process.WaitForExit); waitForExitDel.BeginInvoke(new AsyncCallback(TaskFinished), null); // Also read outputs on the threadpool ThreadStart readOutputDel = new ThreadStart(this.ReadOutput); ThreadStart readErrorDel = new ThreadStart(this.ReadError); readOutputDel.BeginInvoke(new AsyncCallback(this.TaskFinished), null); readErrorDel.BeginInvoke(new AsyncCallback(this.TaskFinished), null); }
public void Execute(IWorker[] workers, int runningSecs) { IAsyncResult[] ar = new IAsyncResult[workers.Length]; int i = 0; foreach (IWorker w in workers) { w.WorkerID = i; ThreadStart t = new ThreadStart(w.DoWork); ar[i++] = t.BeginInvoke(null, null); } //for (int j = 0; j < runningSecs * 10; j++) //{ // Console.Write("."); // Thread.Sleep(100); //} Thread.Sleep(runningSecs * 1000); Console.WriteLine(); foreach (IWorker w in workers) { w.Running = false; } bool timeOut = false; foreach (IAsyncResult a in ar) { if (!a.IsCompleted) { if (!a.AsyncWaitHandle.WaitOne(1000)) timeOut = true; } } if (timeOut) Console.WriteLine("Timed Out!"); }
static void Main(string[] args) { Console.WriteLine("Main Thread's managed thread id: " + Thread.CurrentThread.ManagedThreadId.ToString()); //The following region shows serval ways to create a thread //The first way directly create a new thread manually //The second and third way run the target function from a thread pool //Second way has the best performance. //The forth way invokes a parameterized function within the new thread //Method1: Create a thread by new Thread object ThreadStart ts1 = new ThreadStart(ThreadFunction1); Thread t1 = new Thread(ts1); t1.Start(); //Method2: Create a thread by ThreadPool.QueueUserWorkItem ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadFunction2)); //Method3: Create a thread by ThreadStart.BeginInvoke; ThreadStart ts2 = new ThreadStart(ThreadFunction3); ts2.BeginInvoke(null, null); //Method4: Create a thread with ParameterizedThreadStart pts = new ParameterizedThreadStart(ThreadFunction4); Thread t2 = new Thread(pts); t2.Start("Message"); Console.ReadKey(); }
public void RealizarImportacao(string pCaminhoDoArquivoDeDados) { gImportacoesParaRealizar = new List <ResultadoDeImportacao>(); ResultadoDeImportacao lResultado; if (pCaminhoDoArquivoDeDados.EndsWith("\\")) { string[] lCaminhos = Directory.GetFiles(pCaminhoDoArquivoDeDados); foreach (string lCaminho in lCaminhos) { if (!lCaminho.EndsWith(".importado")) //arquivos ".importado" são os que já foram importados { lResultado = new ResultadoDeImportacao(lCaminho); gImportacoesParaRealizar.Add(lResultado); } } } else { gImportacoesParaRealizar.Add(new ResultadoDeImportacao(pCaminhoDoArquivoDeDados)); } OnMensagem("[{0}] arquivo{1} para importar.", gImportacoesParaRealizar.Count, gImportacoesParaRealizar.Count > 0 ? "s" : ""); ThreadStart lThread = new ThreadStart(RealizarImportacoes); lThread.BeginInvoke(null, null); OnMensagem("Thread de importações iniciado."); }
public void TestCallLevelLocking() { BPlusTree <int, int> .OptionsV2 options = new BPlusTree <int, int> .OptionsV2( new PrimitiveSerializer(), new PrimitiveSerializer()); options.LockTimeout = 100; options.CallLevelLock = new ReaderWriterLocking(); using (BPlusTree <int, int> dictionary = new BPlusTree <int, int>(options)) { bool canwrite = false, canread = false; ThreadStart proc = delegate() { try { dictionary[1] = 1; canwrite = true; } catch { canwrite = false; } try { int i; dictionary.TryGetValue(1, out i); canread = true; } catch { canread = false; } }; Assert.IsTrue(proc.BeginInvoke(null, null).AsyncWaitHandle.WaitOne(1000, false)); Assert.IsTrue(canwrite); Assert.IsTrue(canread); //now we lock the entire btree: using (dictionary.CallLevelLock.Write()) { //they can't read or write Assert.IsTrue(proc.BeginInvoke(null, null).AsyncWaitHandle.WaitOne(1000, false)); Assert.IsFalse(canwrite); Assert.IsFalse(canread); //but we can proc(); Assert.IsTrue(canwrite); Assert.IsTrue(canread); } //lock release all is well Assert.IsTrue(proc.BeginInvoke(null, null).AsyncWaitHandle.WaitOne(1000, false)); Assert.IsTrue(canwrite); Assert.IsTrue(canread); //We can also make sure noone else gains exclusive access with a read lock using (dictionary.CallLevelLock.Read()) { Assert.IsTrue(proc.BeginInvoke(null, null).AsyncWaitHandle.WaitOne(1000, false)); Assert.IsTrue(canwrite); Assert.IsTrue(canread); } } }
public void SingleButton(object sender, EventArgs args) { //Create new server in new thread // load client gameplayscreen ThreadStart test = new ThreadStart(serverStart); test.BeginInvoke(null, null); ScreenManager.AddScreen(new UserInterface.Screens.GamePlayScreen("127.0.0.1", 28000)); }
/// <summary> /// Extends BeginInvoke so that when a state object is not needed, null does not need to be passed. /// <example> /// threadstart.BeginInvoke(callback); /// </example> /// </summary> public static IAsyncResult BeginInvoke(this ThreadStart threadstart, AsyncCallback callback) { if (threadstart == null) { throw new ArgumentNullException("threadstart"); } return(threadstart.BeginInvoke(callback, null)); }
public void LoadAsync() { if (load_completed) { return; } ThreadStart async = new ThreadStart(Load); async.BeginInvoke(AsyncFinished, async); }
public void AbortAsync() { ThrowIfAbortNotEnabled(); if (!AbortPending) { AbortPending = true; var abortThreadStart = new ThreadStart(Abort); abortThreadStart.BeginInvoke(null, null); } }
private void button1_Click(object sender, EventArgs e) { btnGo.Enabled = false; ItemCount = 0; CurrentLevel = cmbLevels.SelectedIndex - 1; Path = new Stack <SimpleGeoName>(); ThreadStart t = GetNodes; t.BeginInvoke(Finished, null); }
/// <summary> /// Fully self contained method that sends email by just sending /// without waiting for confirmation by starting a new thread /// </summary> /// <returns></returns> public void SendMailAsync() { ThreadStart oDelegate = new ThreadStart(SendMailRun); // Thread myThread = new Thread(oDelegate); // myThread.Start(); /// If you want to use the Thread Pool you can just use a delegate /// This will often be faster and more efficient especially for quick operations oDelegate.BeginInvoke(null, null); }
/// ///////////////////////////////////////////////////////////////// public static void StartThreadWithProgress(string strTitre, ThreadStart fonctionDemarrage) { if (m_form == null) { m_form = new CFormProgression(); } m_form.ResetSegmentsProgression(); m_form.TopMost = true; m_form.m_labelText.Text = strTitre; m_form.Show(); fonctionDemarrage.BeginInvoke(new AsyncCallback(m_form.OnEndProcess), null); }
public ThreadedWriter(ILockStrategy lck) { _started = new ManualResetEvent(false); _complete = new ManualResetEvent(false); _lck = lck; _delegate = HoldLock; _async = _delegate.BeginInvoke(null, null); if (!_started.WaitOne(1000, false)) { _delegate.EndInvoke(_async); Assert.Fail("Unable to acquire lock"); } Assert.IsTrue(_locked); }
public ThreadedWriter(ILockStrategy lck) { _started = new ManualResetEvent(false); _complete = new ManualResetEvent(false); _lck = lck; _delegate = HoldLock; _async = _delegate.BeginInvoke(null, null); if (!_started.WaitOne(1000, false)) { _delegate.EndInvoke(_async); Assert.Fail("Unable to acquire lock"); } Assert.IsTrue(_locked); }
public void Play() { var DoWork = new ThreadStart(delegate { if (_stream == 0 && _currentSong != null && !string.IsNullOrEmpty(_currentSong.FileName)) { // Try to reload the current file LoadFile(_currentSong.FileName); Play(); } else if (_stream != 0) { try { Bass.BASS_ChannelPlay(_stream, false); foreach (int freq in _lastEqualizerValues.Keys.ToArray()) { SetEqualizerPosition(freq, _lastEqualizerValues[freq]); } if (_playingStream) { if (_lib != null) { _lib.UpdatePlayCount(_currentSong.FileName); } } else { _timer.Start(); } this.State = PlayerState.Playing; } catch (Exception ex) { // Um...what's going on here?! //System.Diagnostics.Debugger.Break(); System.Diagnostics.Debug.WriteLine("Exception: " + ex.Message); Next(); } } else { Next(); } }); DoWork.BeginInvoke(null, null); }
public void Run(String fileName, String arguments, Boolean shellCommand) { if (isRunning) { // kill process and queue Run command nextTask = () => { Run(fileName, arguments, shellCommand); }; this.KillProcess(); return; } if (!shellCommand && !File.Exists(fileName)) { throw new FileNotFoundException("The program '" + fileName + "' was not found.", fileName); } isRunning = true; process = new Process(); process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = RedirectInput; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.StandardOutputEncoding = Encoding.Default; process.StartInfo.StandardErrorEncoding = Encoding.Default; process.StartInfo.CreateNoWindow = true; process.StartInfo.FileName = fileName; process.StartInfo.Arguments = arguments; process.StartInfo.WorkingDirectory = WorkingDirectory ?? PluginBase.MainForm.WorkingDirectory; process.Start(); outputReader = process.StandardOutput; errorReader = process.StandardError; // we need to wait for all 3 threadpool operations // to finish (processexit, readoutput, readerror) tasksFinished = 0; ThreadStart waitForExitDel = new ThreadStart(process.WaitForExit); waitForExitDel.BeginInvoke(new AsyncCallback(TaskFinished), null); ThreadStart readOutputDel = new ThreadStart(ReadOutput); ThreadStart readErrorDel = new ThreadStart(ReadError); readOutputDel.BeginInvoke(new AsyncCallback(TaskFinished), null); readErrorDel.BeginInvoke(new AsyncCallback(TaskFinished), null); }
public RoleViewModel() { InitializeCommands(); GridDisplaySelected = true; RaisePropertyChanged("GridDisplaySelected"); PageTitle = Application.Current.MainWindow.Resources["txtAddRole"].ToString(); RaisePropertyChanged("PageTitle"); SelectedRole = new OrgRoleDTO(); RaisePropertyChanged("SelectedRole"); ThreadStart ts = new ThreadStart(FetchData); Thread t = new Thread(ts); ts.BeginInvoke(null, null); }
public void PlayFile(string file) { var DoWork = new ThreadStart(delegate { if (LoadFile(file)) { Play(); } else { Next(); } }); DoWork.BeginInvoke(null, null); }
private void LoadFoundstoneXsmlAdds() { string strPathToLocalCopyOfXmlFile = Path.Combine(MapPath("~/xml/"), "info.xml"); string strSourceInformation = ""; try { string strTest = Session["FoundstoneMaketingMaterial"].ToString(); if (Session["FoundstoneMaketingMaterial"].ToString() == "") { // return; // comment here to disable this test XPathDocument myXPathDoc; // we are going to start a new thread and give it 500ms to complete (this is thread we open a TCP connection to www.foundstone.com) bAreWeOnline = false; ThreadStart tsAreWeOnline = new ThreadStart(checkIfWeAreOnline); tsAreWeOnline.BeginInvoke(null, null); Thread.Sleep(500); if (bAreWeOnline) // if the tcp connection was succssfull we are online { //Response.Write("<hr/> We are online <hr/>"); myXPathDoc = new XPathDocument(strPathToWebCopyXmlFile); strSourceInformation = " <i>[The information below is up-to-date and was downloaded from the foundstone website]</i><br>"; } else { //Response.Write("<hr/> We are NOT online <hr/>"); myXPathDoc = new XPathDocument(strPathToLocalCopyOfXmlFile); strSourceInformation = " <i>[ The current computer is not online, so the information below might be out-of-date]</i><br>"; } // now that we have a file to work on (either the dynamic from the website of the one local) we can can do the transformation XslTransform myXslTrans = new XslTransform(); myXslTrans.Load(Path.Combine(MapPath(Gui.pathToXslFolder), "info.xsl")); MemoryStream msXslTrans = new MemoryStream(); myXslTrans.Transform(myXPathDoc, null, msXslTrans, new XmlUrlResolver()); msXslTrans.Flush(); msXslTrans.Position = 0; // after store the transformation in a session variable so that we don't have to do this everytime Session["FoundstoneMaketingMaterial"] = (new StreamReader(msXslTrans)).ReadToEnd(); } lbXmlInformation.Text = strSourceInformation + Session["FoundstoneMaketingMaterial"].ToString(); } catch (Exception ex) { Response.Write("<hr/>LoadFoundstoneXsmlAdds: " + ex.Message + "<hr/>"); } }
public void GenerateCGImagesAsynchronously_Compat() { handled = false; mre = new ManualResetEvent(false); ThreadStart main = () => { using (NSUrl video_url = NSUrl.FromFilename(video_asset_path)) using (AVAsset video_asset = AVAsset.FromUrl(video_url)) using (AVAssetImageGenerator aig = new AVAssetImageGenerator(video_asset)) { aig.GenerateCGImagesAsynchronously(NSValue.FromCMTime(CMTime.Zero), handler); mre.WaitOne(); } }; var asyncResult = main.BeginInvoke(null, null); main.EndInvoke(asyncResult); Assert.True(mre.WaitOne(2000)); Assert.True(handled, "handled"); }
public void SetupAsync() { if (IsBusy) { return; } this.dataGridViewUpdates.Rows.Clear(); releases = null; timerImgAnimate.Start(); this.Invalidate(); this.Refresh(); ThreadStart ts = new ThreadStart(SetupAndBuildReleaseList); asyncres = ts.BeginInvoke(new AsyncCallback(SetupAsyncCompleted), null); }
public void RunAsyncOperation(string statusText, Action operation, Action completed, object userState) { if (this.IsBusy) { throw new InvalidOperationException("AsyncNode is busy."); } this.IsBusy = true; var originalText = this.Text; this.Text = originalText + " (" + statusText + "...)"; ThreadStart action = delegate { Exception error = null; try { operation(); } catch (Exception exception) { error = exception; } finally { this.IsBusy = false; } ThreadStart finish = delegate { this.Text = originalText; if (error == null) { completed(); } else { this.OnAsyncException(new AsyncCompletedEventArgs(error, false, userState)); } }; if (this.TreeView != null) { this.TreeView.Invoke(finish); } else { finish(); } }; action.BeginInvoke(null, null); }
static void Main(string[] args) { var path = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "log.txt"); var ini_path = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "config.ini"); var del = new ThreadStart(() => { var lines = File.ReadAllLines(ini_path); try { if (lines.Length >= 2) { System.Diagnostics.Process.Start(lines[0], lines[1]); } } catch (Exception e) { File.AppendAllText(path, DateTime.Now.ToString() + string.Format("异常:{0}\r\n", e.Message)); } while (true) { try { File.AppendAllText(path, DateTime.Now.ToString() + string.Format(" {0}\r\n", lines[0])); //保留半个小时的日志 if (DateTime.Now - File.GetCreationTime(path) > new TimeSpan(0, 30, 0)) { File.Delete(path); } } catch (Exception e) { File.AppendAllText(path, DateTime.Now.ToString() + string.Format("异常:{0}\r\n", e.Message)); } Console.WriteLine(DateTime.Now); Int32 sleep_time = 1000; Thread.Sleep(sleep_time); } }); del.BeginInvoke(null, null); Console.Read(); }
public void PlayLooping() { if (!use_win32_player) { ThreadStart async = new ThreadStart(PlayLoop); async.BeginInvoke(AsyncFinished, async); } else { Start(); if (mstream == null) { SystemSounds.Beep.Play(); return; } win32_player.PlayLooping(); } }
public void Run(string fileName, string arguments) { if (isRunning) { throw new Exception("This ProcessRunner is already running a process."); } if (!File.Exists(fileName)) { throw new FileNotFoundException("The program '" + fileName + "' was not found.", fileName); } isRunning = true; process = new Process(); process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.CreateNoWindow = true; process.StartInfo.FileName = fileName; process.StartInfo.Arguments = arguments; process.StartInfo.WorkingDirectory = Environment.CurrentDirectory; process.Start(); outputReader = process.StandardOutput; errorReader = process.StandardError; // we need to wait for all 3 of our threadpool operations to finish // (processexit, readoutput, readerror) tasksFinished = 0; // do our waiting on the threadpool ThreadStart waitForExitDel = new ThreadStart(process.WaitForExit); waitForExitDel.BeginInvoke(new AsyncCallback(TaskFinished), null); // also read outputs on the threadpool ThreadStart readOutputDel = new ThreadStart(ReadOutput); ThreadStart readErrorDel = new ThreadStart(ReadError); readOutputDel.BeginInvoke(new AsyncCallback(TaskFinished), null); readErrorDel.BeginInvoke(new AsyncCallback(TaskFinished), null); }
public void Next() { var DoWork = new ThreadStart(delegate { bool success = false; if (!success) { success = TryToLoadAndPlay(GetForceSong); } if (!success) { success = TryToLoadAndPlay(GetFileFromPlaylist); } if (!success) { success = TryToLoadAndPlay(GetRandomSong); } }); DoWork.BeginInvoke(null, null); }
public void Previous() { var DoWork = new ThreadStart(delegate { if (_history.Count > 0) { string prevFile = _history.Pop(); if (LoadFile(prevFile)) { Play(); _history.Pop(); } else { Next(); } } }); DoWork.BeginInvoke(null, null); }
public void Execute(IWorker[] workers, int runningSecs) { IAsyncResult[] ar = new IAsyncResult[workers.Length]; int i = 0; foreach (IWorker w in workers) { ThreadStart t = new ThreadStart(w.DoWork); ar[i++] = t.BeginInvoke(null, null); } /* for (int j = 0; j < runningSecs*10; j++) { Console.Write("."); Thread.Sleep(100); }*/ Thread.Sleep(runningSecs * 1000); Console.WriteLine("--------------- Time running finished!!!!"); foreach (IWorker w in workers) { w.Running = false; } foreach (IAsyncResult a in ar) { if (!a.IsCompleted) a.AsyncWaitHandle.WaitOne(); } }
private void cmdBeClient_Click(object sender, System.EventArgs e) { //*********************** Client Attempt ****************************************** //amIClient = true; cmdFindClients.Enabled = false; ThreadStart myThreadStart = new ThreadStart(client); System.IAsyncResult m = null; m = myThreadStart.BeginInvoke(new AsyncCallback(caller),null); }
public void SetupAsync() { if (IsBusy) return; this.dataGridViewUpdates.Rows.Clear(); releases = null; timerImgAnimate.Start(); this.Invalidate(); this.Refresh(); ThreadStart ts = new ThreadStart(SetupAndBuildReleaseList); asyncres = ts.BeginInvoke(new AsyncCallback(SetupAsyncCompleted), null); }
private void LoadFoundstoneXsmlAdds() { string strPathToLocalCopyOfXmlFile = Path.Combine(MapPath("~/xml/"),"info.xml"); string strSourceInformation = ""; try { string strTest = Session["FoundstoneMaketingMaterial"].ToString(); if (Session["FoundstoneMaketingMaterial"].ToString()=="") { // return; // comment here to disable this test XPathDocument myXPathDoc; // we are going to start a new thread and give it 500ms to complete (this is thread we open a TCP connection to www.foundstone.com) bAreWeOnline = false; ThreadStart tsAreWeOnline = new ThreadStart(checkIfWeAreOnline); tsAreWeOnline.BeginInvoke(null,null); Thread.Sleep(500); if (bAreWeOnline) // if the tcp connection was succssfull we are online { //Response.Write("<hr/> We are online <hr/>"); myXPathDoc = new XPathDocument(strPathToWebCopyXmlFile); strSourceInformation = " <i>[The information below is up-to-date and was downloaded from the foundstone website]</i><br>"; } else { //Response.Write("<hr/> We are NOT online <hr/>"); myXPathDoc = new XPathDocument(strPathToLocalCopyOfXmlFile); strSourceInformation = " <i>[ The current computer is not online, so the information below might be out-of-date]</i><br>"; } // now that we have a file to work on (either the dynamic from the website of the one local) we can can do the transformation XslTransform myXslTrans = new XslTransform() ; myXslTrans.Load(Path.Combine(MapPath(Gui.pathToXslFolder),"info.xsl")); MemoryStream msXslTrans = new MemoryStream(); myXslTrans.Transform(myXPathDoc,null,msXslTrans, new XmlUrlResolver()) ; msXslTrans.Flush(); msXslTrans.Position= 0; // after store the transformation in a session variable so that we don't have to do this everytime Session["FoundstoneMaketingMaterial"] = (new StreamReader(msXslTrans)).ReadToEnd(); } lbXmlInformation.Text = strSourceInformation + Session["FoundstoneMaketingMaterial"].ToString(); } catch (Exception ex) { Response.Write("<hr/>LoadFoundstoneXsmlAdds: " + ex.Message + "<hr/>"); } }
public void PlayLooping () { if (!use_win32_player) { ThreadStart async = new ThreadStart (PlayLoop); async.BeginInvoke (AsyncFinished, async); } else { Start (); if (mstream == null) { SystemSounds.Beep.Play (); return; } win32_player.PlayLooping (); } }
public void LoadAsync () { if (load_completed) return; ThreadStart async = new ThreadStart (Load); async.BeginInvoke (AsyncFinished, async); }
/// <summary> /// カレントスレッドプールで非同期に関数を実行します。 /// </summary> /// <param name="start"></param> public static void Call(ThreadStart start) { start.BeginInvoke(delegate(IAsyncResult ar) { return; }, null); }
private void button1_Click_1(object sender, System.EventArgs e) { //start a new thread running doServerStuff() ThreadStart myThreadStart = new ThreadStart(doServerStuff); System.IAsyncResult m = null; m = myThreadStart.BeginInvoke(new AsyncCallback(caller),null); }
/// <summary> /// Fully self contained method that sends email by just sending /// without waiting for confirmation by starting a new thread /// </summary> /// <returns></returns> public void SendMailAsync() { ThreadStart oDelegate = new ThreadStart(SendMailRun); // Thread myThread = new Thread(oDelegate); // myThread.Start(); /// If you want to use the Thread Pool you can just use a delegate /// This will often be faster and more efficient especially for quick operations oDelegate.BeginInvoke(null, null); }
private void bt4_Click(object sender, EventArgs e) { b = new StringBuilder(); ThreadStart ts = new ThreadStart(t1Start); IAsyncResult r1 = ts.BeginInvoke(null, null); IAsyncResult r2 = ts.BeginInvoke(null, null); ts.EndInvoke(r1); ts.EndInvoke(r2); tbOut.Text = b.ToString(); }
private void Form1_Load(object sender, EventArgs e) { foreach (string name in names) { ToolStripMenuItem tsi = new ToolStripMenuItem(name); tsi.Click += ToolStripMenuItem_Click; contextMenuStrip1.Items.Add(tsi); } if (!File.Exists(strDownloadPath + "\\trainedImages.xml")) return; string xml = File.ReadAllText(strDownloadPath + "\\trainedImages.xml"); trainedFaces = (SeDes.ToObj(xml, trainedFaces) as List<trainedFace>); ThreadStart ts = new ThreadStart(fixFaces); progressBar1.Visible = true; IAsyncResult iar = ts.BeginInvoke((AsyncCallback) => { this.Invoke((MethodInvoker)delegate { progressBar1.Visible = false; }); }, null); }
public void Start() { thread = new ThreadStart(QueryFrame); IsRunning = true; thread.BeginInvoke(null, null); }