public static BackgroundWorker WithHandlers(this BackgroundWorker bw, DoWorkDelegate doWorkDelegate, ProgressChangedDelegate progressChangedDelegate, RunWorkerCompletedDelegate runWorkerCompletedDelegate) { bw.DoWork += new DoWorkEventHandler((sender, dwe) => { doWorkDelegate(dwe); }); bw.ProgressChanged += new ProgressChangedEventHandler((sender, pce) => { progressChangedDelegate(pce); }); bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler((sender, rwce) => { runWorkerCompletedDelegate(rwce); }); return bw; }
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { // Do not access the form's BackgroundWorker reference directly. // Instead, use the reference provided by the sender parameter. BackgroundWorker bw = (BackgroundWorker)sender; try { if (!doWorkAdded) { doWorkDelegate += backgroundWork.DoBackgroundWork; doWorkAdded = true; } doWorkDelegate(); } catch (WorkerCanceledException) { // This exception is throw only to stop the execution of the method delegated to doWorkDelegate } finally { // If the operation was canceled by the user, // set the DoWorkEventArgs.Cancel property to true. if (bw.CancellationPending) { e.Cancel = true; } } }
static void Main() { DoWorkDelegate del = DoWork; // Note: У вас есть два способа получить уведомление об окончании метода: // Note: 1) Через метод обратного вызова IAsyncResult asyncResult = del.BeginInvoke(100000000, stateObject => Console.WriteLine("Computation done"), // Фактически никакое состояние передано не было null); for (int i = 0; i < 5; i++) { Console.WriteLine("Doing other work...{0}", i); Thread.Sleep(1000); } // Note: 2) С помощью EndInvoke double sum = del.EndInvoke(asyncResult); // Дождаться окончания Console.WriteLine("Sum: {0}", sum); Console.ReadKey(); }
private void SendFileRun(String filePath) { DisableStartButtons(); DoWorkDelegate worker = new DoWorkDelegate(SendFile); worker.BeginInvoke(filePath, new AsyncCallback(DoWorkComplete), worker); }
private void DoWorkComplete(IAsyncResult workID) { EnableStartButtons(); DoWorkDelegate worker = workID.AsyncState as DoWorkDelegate; worker.EndInvoke(workID); }
/// <summary> /// Выполняет операцию в фоновом потоке, не блокируя UI элементы формы. Может быть вызван сколько угодно раз подряд /// </summary> /// <param name="args">Начальные аргументы для потока</param> /// <param name="action">Метод, выполняемый в фоновом потоке</param> /// <param name="progress">Метод, выполняемый в фоновом потоке, позволяющий откликаться в основной поток</param> /// <param name="completed">Метод, выполняемый после окончания фонового потока</param> /// <param name="cancellationToken">Токен для воркеров с возможностью остановки</param> public static void RunAsync(object args, DoWorkDelegate action, ProgressDelegate progress, CompletedDelegate completed, CancellationTokenSource cancellationToken = null) { Worker w = new Worker(args, action, completed, progress, progress != null, cancellationToken); w.Complited += new EventHandler(w_Complited); Count++; }
private void ActButton_Click(object sender, RoutedEventArgs e) { DoWorkDelegate d = new DoWorkDelegate(DoSlowWork); DoSlowWork(); Output.Content = "Changed!"; }
private IAsyncResult BeginLoadSlowContent(Object src, EventArgs args, AsyncCallback cb, Object state) { System.Diagnostics.Trace.WriteLine("BeginLoadSlowContent " + Thread.CurrentThread.ManagedThreadId); _doWork = LoadProductList; return _doWork.BeginInvoke(cb, state); }
//--------------------------------------------------- public static void DoWork(DoWorkDelegate funcToCall) { CFormWaiting frm = new CFormWaiting(); frm.m_funcToCall = funcToCall; frm.ShowDialog(); }
public void Demo01() { Debug.WriteLine($"Current executing thread ID of Demo01 unit test method is: {Thread.CurrentThread.ManagedThreadId.ToString()}"); // With a delegate instead of calling DoWork directly //DoWork(); // We can do this DoWorkDelegate doWorkDelegate = new DoWorkDelegate(DoWork); // The delegate keyword behind the scene is generating a whole class //doWorkDelegate(); // or doWorkDelegate.Invoke(); // So doWorkDelegate is actually an object that has methods in it // With this we can introduce asynchronous code like the begin/end pattern AsyncCallback asyncCallback = new AsyncCallback(TheCallback); IAsyncResult ar = doWorkDelegate.BeginInvoke(asyncCallback, doWorkDelegate); // do more work var result = 1 + 2; Debug.WriteLine($"Result is {result}"); ar.AsyncWaitHandle.WaitOne(); }
public LoadBalancingBroker(LoadBalancingSettings settings, DoWorkDelegate doWork) { LoadBalancingSettings = settings; InitializeWorkerList(doWork); LoadBalancingSettings.LoadBalancer = InstantiateLoadBalancer(); ((AbstractLoadBalancer)LoadBalancingSettings.LoadBalancer).SetWorkers(new LinkedList <IWorker>(this)); }
public void Start() { Console.WriteLine("Started."); DoWorkDelegate d = FindThemClones; d.BeginInvoke(CodeText, WhenDoneCallback, d); }
/// <summary> /// Выполняет операцию в фоновом потоке, не блокируя UI элементы формы. Может быть вызван сколько угодно раз подряд /// </summary> /// <param name="args">Начальные аргументы для потока</param> /// <param name="action">Метод, выполняемый в фоновом потоке</param> /// <param name="cancellationToken">Токен для воркеров с возможностью остановки</param> public static void RunAsync(object args, DoWorkDelegate action, CancellationTokenSource cancellationToken = null) { Worker w = new Worker(args, action, null, null, false, cancellationToken); w.Complited += new EventHandler(w_Complited); Count++; }
private void WhenDoneCallback(IAsyncResult ar) { DoWorkDelegate d = (DoWorkDelegate)ar.AsyncState; ScanResult scanResult = d.EndInvoke(ar); InvokeJobDone(scanResult); }
public CancellableTask(DoWorkDelegate doWork, TaskCompletedDelegate completed) : this(new BackgroundWorker()) { this._doWork = doWork; this._completed = completed; this._worker.DoWork += new DoWorkEventHandler(this._doWork); this._worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(this._completed); }
public void CheckDelegateAsyncOperation() { Debug.WriteLine($"Demo One Thread: {Thread.CurrentThread.ManagedThreadId}"); var doWork = new DoWorkDelegate(DoWork); var asyncCallback = new AsyncCallback(TheCallBack); var asyncResult = doWork.BeginInvoke(asyncCallback, doWork); asyncResult.AsyncWaitHandle.WaitOne(); }
public LoadBalancingBroker(ILogger logger, string name, DoWorkDelegate doWork, LoadBalancingSettings settings) { _logger = logger; Name = name; Settings = settings; InitializeWorkerList(doWork); Settings.LoadBalancer = InstantiateLoadBalancer(); ((AbstractLoadBalancer)Settings.LoadBalancer).SetWorkers(new LinkedList <IWorker>(this)); }
private void InitializeWorkerList(DoWorkDelegate doWork) { AddRange( Enumerable.Range(0, Settings.NumberOfWorkers).Select(index => new Worker <TEntity>(index, Settings.BoundedCapacityByWorker, Settings.CancellationToken) { DoWork = doWork }).ToList()); }
public void TestDelegateInvoke() { Debug.WriteLine($"Hello from TestDelegateCall() (Thread ID: {Thread.CurrentThread.ManagedThreadId})"); // Create the delegate. var caller = new DoWorkDelegate(DoSimpleWork); // Call the delegated method on the same thread. caller(); }
private void InitializeWorkerList(DoWorkDelegate doWork) { for (var index = 0; index < LoadBalancingSettings.NumberOfWorkers; index++) { var worker = new Worker <TEntity>(index, 100, LoadBalancingSettings.CancellationToken) { DoWork = doWork }; Add(worker); } }
public void Demo01() { Debug.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId.ToString()); DoWorkDelegate m = new DoWorkDelegate(DoWork); AsyncCallback callback = new AsyncCallback(TheCallback); IAsyncResult ar = m.BeginInvoke(callback, m); // do more ar.AsyncWaitHandle.WaitOne(); }
private void AppendSuccess(string msg) { if (this.InvokeRequired) { DoWorkDelegate dg = new DoWorkDelegate(AppendSuccess); this.Invoke(dg, new object[] { msg }); } else { vsubdwnldr.Items.Insert(0, msg); } }
public void Demo1() { Debug.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId.ToString()); DoWorkDelegate m = new DoWorkDelegate(DoWork); AsyncCallback callback = new AsyncCallback(TheCallback); // The Begin - End Pattern for Asyncronous Processing IAsyncResult ar = m.BeginInvoke(callback, m); //Do Work ar.AsyncWaitHandle.WaitOne(); }
/// <summary> /// Start asyncronous check. /// </summary> public void Start() { try { DoWorkDelegate WorkerThread = new DoWorkDelegate(DoWork); WorkerThread.BeginInvoke(m_ComponentIndex, new AsyncCallback(DoWorkComplete), WorkerThread); } catch (Exception ex) { OnError(ex, "ASynchCheckBase.Start"); } }
public void TestBeginEndPatternWithCallbackAbortException() { Debug.WriteLine($"Hello from TestBeginEndPatternWithCallbackAbortException() (Thread ID: {Thread.CurrentThread.ManagedThreadId})"); var doWork = new DoWorkDelegate(DoHardWork); var callback = new AsyncCallback(Callback); IAsyncResult ar = doWork.BeginInvoke(callback, doWork); Debug.WriteLine($"End of main thread (Thread ID: {Thread.CurrentThread.ManagedThreadId})"); // Will rise ThreadAbortException on the second thread. }
private void Labelchange(int cnt, string Filename) { if (this.InvokeRequired) { DoWorkDelegate dg = new DoWorkDelegate(Labelchange); this.Invoke(dg, new object[] { cnt, Filename }); } else { label4.Text = cnt + " Bhavcopy Downloaded"; rCT1.Text += Filename + " Fetched \n\n"; } }
public void doWorkDelegateAsyncTest() { Debug.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId.ToString()); DoWorkDelegate doingwork = new DoWorkDelegate(doWork); // BeginInvoke will execute method in different thread AsyncCallback asyncCallback = new AsyncCallback(callback); IAsyncResult ar = doingwork.BeginInvoke(asyncCallback, doingwork); // Do work in main thread here //doingwork.EndInvoke(ar); }
public Guid?Chat(string sender, string reciever) //Adds a chat session to reciever { try { DoWorkDelegate del = SendMessagesListToClient; return(OpenSession(sender, reciever, del)); } catch (Exception e) { Report($"Could not open a chat with {reciever}", LogLevel.Exception); Report(e.Message, LogLevel.Exception); return(null); } }
public Guid?RequestNewGame(string sender, string reciever) { try { DoWorkDelegate del = SendGameToClient; Report($"Game request sent to {reciever}", LogLevel.Information); return(OpenSession(sender, reciever, del)); } catch (Exception e) { Report($"Could not open a game with {reciever}", LogLevel.Exception); Report(e.Message, LogLevel.Exception); return(null); } }
// What is a delegate // ================== // A delegate is a type that represents references to methods with a particular parameter list and return type. public void Main() { //Assigning an existing function DoWorkDelegate doWorkDelegate = DoWork; //Assigning to an anonymous method (C# 2.0) DoWorkDelegate anonymousFunctionDelegate = delegate() { Console.WriteLine("Work done from anonymous function !"); }; //Assigning to an anonymous method (C# 3.0) DoWorkDelegate lambdaDelegate = () => Console.WriteLine("Work done from lambda expression !"); //Invoking a delegate's method doWorkDelegate.Invoke(); anonymousFunctionDelegate.Invoke(); lambdaDelegate.Invoke(); //Method chaining Console.WriteLine(); Console.WriteLine("Method chaining"); Console.WriteLine("=================="); doWorkDelegate += DoOtherWork; doWorkDelegate.Invoke(); //Using a delegate with params and a return type Console.WriteLine(); Console.WriteLine("Delegate with params and a return type"); Console.WriteLine("=================="); DoWorkAndReturnStuffDelegate delegateWithParamsAndReturnType = DoWorkAndReturnStuff; string result = delegateWithParamsAndReturnType.Invoke("Test input"); Console.WriteLine($"Delegate invocation result: {result}"); }
public void TestBeginEndPatternWithCallback() { Debug.WriteLine($"Hello from TestBeginEndPatternWithCallback() (Thread ID: {Thread.CurrentThread.ManagedThreadId})"); var doWork = new DoWorkDelegate(DoHardWork); var callback = new AsyncCallback(Callback); IAsyncResult ar = doWork.BeginInvoke(callback, doWork); // The callback is made on a ThreadPool thread. ThreadPool threads // are background threads, which do not keep the application running // if the main thread ends. Thread.Sleep(2000); Debug.WriteLine($"End of main thread (Thread ID: {Thread.CurrentThread.ManagedThreadId})"); }
public Worker(object args, DoWorkDelegate action, CompletedDelegate completedAction, ProgressDelegate progressAction, bool canReport, CancellationTokenSource cancellationToken) { this.bWork = new BackgroundWorker(); this.bWork.WorkerReportsProgress = canReport; this.Action = action; this.CompletedAction = completedAction; this.ProgressAction = progressAction; bWork.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bWork_RunWorkerCompleted); bWork.DoWork += new DoWorkEventHandler(bWork_DoWork); bWork.ProgressChanged += new ProgressChangedEventHandler(bWork_ProgressChanged); if (cancellationToken != null) { bWork.WorkerSupportsCancellation = true; } bWork.RunWorkerAsync(args); }
public static void TestCallMethodWithoutWaitingForReturn() { DoWorkDelegate del = DoWork; //two ways to be notified of when method ends: // 1. callback method // 2. call EndInvoke IAsyncResult res = del.BeginInvoke(100000000, DoWorkDone, null); for (int i = 0; i < 5; i++) { Console.WriteLine("Doing other work...{0}", i); Thread.Sleep(1000); } //wait for end double sum = del.EndInvoke(res); Console.WriteLine("Sum: {0}", sum); }
private void RunBackground(DoWorkDelegate doWork) { backgroundWorker1.RunWorkerAsync(doWork); ShowRunnerStatus(); }