Search Results

Search found 190 results on 8 pages for 'backgroundworker'.

Page 5/8 | < Previous Page | 1 2 3 4 5 6 7 8  | Next Page >

  • Can't get my head around background workers in .NET

    - by Connel
    I have wrote an application that syncs two folders together. The problem with the program is that it stops responding whilst copying files. A quick search of stack-overflow told me I need to use something called a background worker. I have read a few pages on the net about this but find it really hard to understand as I'm pretty new to programming. Below is the code for my application - how can I simply put all of the File.Copy(....) commands into their own background worker (if that's even how it works)? Below is the code for the button click event that runs the sub procedure and the sub procedure I wish to use a background worker on all the File.Copy lines. Button event: protected virtual void OnBtnSyncClicked (object sender, System.EventArgs e) { //sets running boolean to true booRunning=true; //sets progress bar to 0 prgProgressBar.Fraction = 0; //resets values used by progressbar dblCurrentStatus = 0; dblFolderSize = 0; //tests if user has entered the same folder for both target and destination if (fchDestination.CurrentFolder == fchTarget.CurrentFolder) { //creates message box MessageDialog msdSame = new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Close, "You cannot sync two folders that are the same"); //sets message box title msdSame.Title="Error"; //sets respone type ResponseType response = (ResponseType) msdSame.Run(); //if user clicks on close button or closes window then close message box if (response == ResponseType.Close || response == ResponseType.DeleteEvent) { msdSame.Destroy(); } return; } //tests if user has entered a target folder that is an extension of the destination folder // or if user has entered a desatination folder that is an extension of the target folder if (fchTarget.CurrentFolder.StartsWith(fchDestination.CurrentFolder) || fchDestination.CurrentFolder.StartsWith(fchTarget.CurrentFolder)) { //creates message box MessageDialog msdContains = new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Close, "You cannot sync a folder with one of its parent folders"); //sets message box title msdContains.Title="Error"; //sets respone type and runs message box ResponseType response = (ResponseType) msdContains.Run(); //if user clicks on close button or closes window then close message box if (response == ResponseType.Close || response == ResponseType.DeleteEvent) { msdContains.Destroy(); } return; } //gets folder size of target folder FileSizeOfTarget(fchTarget.CurrentFolder); //gets folder size of destination folder FileSizeOfDestination(fchDestination.CurrentFolder); //runs SyncTarget procedure SyncTarget(fchTarget.CurrentFolder); //runs SyncDestination procedure SyncDestination(fchDestination.CurrentFolder); //informs user process is complete prgProgressBar.Text = "Finished"; //sets running bool to false booRunning = false; } Sync sub-procedure: protected void SyncTarget (string strCurrentDirectory) { //string array of all the directories in directory string[] staAllDirectories = Directory.GetDirectories(strCurrentDirectory); //string array of all the files in directory string[] staAllFiles = Directory.GetFiles(strCurrentDirectory); //loop over each file in directory foreach (string strFile in staAllFiles) { //string of just the file's name and not its path string strFileName = System.IO.Path.GetFileName(strFile); //string containing directory in target folder string strDirectoryInsideTarget = System.IO.Path.GetDirectoryName(strFile).Substring(fchTarget.CurrentFolder.Length); //inform user as to what file is being copied prgProgressBar.Text="Syncing " + strFile; //tests if file does not exist in destination folder if (!File.Exists(fchDestination.CurrentFolder + "/" + strDirectoryInsideTarget + "/" + strFileName)) { //if file does not exist copy it to destination folder, the true below means overwrite if file already exists File.Copy (strFile, fchDestination.CurrentFolder + "/" + strDirectoryInsideTarget + "/" + strFileName, true); } //tests if file does exist in destination folder if (File.Exists(fchDestination.CurrentFolder + "/" + strDirectoryInsideTarget + "/" + strFileName)) { //long (number) that contains date of last write time of target file long lngTargetFileDate = File.GetLastWriteTime(strFile).ToFileTime(); //long (number) that contains date of last write time of destination file long lngDestinationFileDate = File.GetLastWriteTime(fchDestination.CurrentFolder + "/" + strDirectoryInsideTarget + "/" + strFileName).ToFileTime(); //tests if target file is newer than destination file if (lngTargetFileDate > lngDestinationFileDate) { //if it is newer then copy file from target folder to destination folder File.Copy (strFile, fchDestination.CurrentFolder + "/" + strDirectoryInsideTarget + "/" + strFileName, true); } } //gets current file size FileInfo FileSize = new FileInfo(strFile); //sets file's filesize to dblCurrentStatus and adds it to current total of files dblCurrentStatus = dblCurrentStatus + FileSize.Length; double dblPercentage = dblCurrentStatus/dblFolderSize; prgProgressBar.Fraction = dblPercentage; } //loop over each folder in target folder foreach (string strDirectory in staAllDirectories) { //string containing directories inside target folder but not any higher directories string strDirectoryInsideTarget = strDirectory.Substring(fchTarget.CurrentFolder.Length); //tests if directory does not exist inside destination folder if (!Directory.Exists(fchDestination.CurrentFolder + "/" + strDirectoryInsideTarget)) { //it directory does not exisit create it Directory.CreateDirectory(fchDestination.CurrentFolder + "/" + strDirectoryInsideTarget); } //run sync on all files in directory SyncTarget(strDirectory); } } Any help will be greatly appreciated as after this the program will pretty much be finished :D

    Read the article

  • wpf do animation until background worker finishes its work

    - by toni
    Hi! I have an application that do some hard stuff when user clicks a start button and takes a long time. During this I would like to do some animation over a label, for example, changing opacity from 0 to 1 and vice versa and change foreground color between several colors at the same time changing opacity. I want it stops doing animation when background worker finishes its work. How can I do this? and how can I start animation and stop it from c#? Thanks very much!

    Read the article

  • Background job with status in rails

    - by pepernik
    Hey. I would like to upload a file and then parse it. Because parsing can take up to 10min I installed delayed_job plugin and called parsing function through send_later function. I have to mention that this is an AJAX app. Imagine that you press an AJAX button that starts upload and after that the source is imported into the database. During the process I want to show the progress bar or message (importing...) and when it completes the task status changes to done. My question is: What is the best way to check for status of the process. What would you do? My idea is to have another controller actions "status" which look into the database and provide the right status.

    Read the article

  • GUI freezing after datagridviews have been updated using backgroundworkers

    - by Jhon
    I have made an application which runs three backgroundworkers simultaneously. It basically updates three datagridviews, which it is doing spot on. My problem is if I press maximizebox button or anywhere in any of the datagridview the program hangs for quite a long time. I am able to use the horizontal scroll but not vertical scrolls. I have tried Backgroundworker_runworkercompleted and it fires as required after threads have updated their respective datagridviews. Is it a normal behaviour or am i doing something wrong any suggestions would be helpful. P.S: I have run the whole program using step method and their is no infinite loop in the code. Thanks in advance Jhon

    Read the article

  • An affordable way to use multiple Delayed::Job queues

    - by NudeCanalTroll
    I have a Ruby on Rails app that needs process many background jobs simultaneously: anywhere from 5-6 at a time to up to 50-60 at a time depending on the time of day. Right now my app is running on Heroku, which charges $.05/hour per worker, regardless of how much CPU or memory the worker is using. This is costing me a boatload each month... up to $1200/mo. Are there any hosts that will allow me to do what I'm doing for significantly cheaper?

    Read the article

  • How to write async background workers that work on WPF flowdocument

    - by iBe
    I'm trying to write a background worker that processes a flowdocument. I can't access the properties of flowdocument objects because of the thread verification. I tried to serialize the document and loaded it on the worker thread which actually solved the thread verfication issue. However, once the processing is complete I also need to use things like TextPointer objects. Those objects now point to a objects in the copy not the original. Can anyone suggest the best way to approach such background processing in WPF?

    Read the article

  • Multi-Threading in .NET

    - by AIC
    Hi all.. I wrote this program, that is supposed to read about 5000 email address and send an pre-defined html mail. I am using the background worker component. The problem is this: I have wired up the method who is supposed to send the mail. But I am calling another method that is supposed to append the body html to the salutation, like public string GiveMeFullHtml(string personname) ... "Dear Mr. John Doe" + HTML ... It seems that when it hits this method call, operation completes. IUt only sends the first mail and completes. I think because the HTML string method is on another thread or sth like that. Can you give me a little insight. Do I have to get everything done in the very same method when using multi-threading? Thanks in advance

    Read the article

  • How to implement cancellable worker thread

    - by Arnold Zokas
    Hi, I'm trying to implement a cancellable worker thread using the new threading constructs in System.Threading.Tasks namespace. So far I have have come up with this implementation: public sealed class Scheduler { private CancellationTokenSource _cancellationTokenSource; public System.Threading.Tasks.Task Worker { get; private set; } public void Start() { _cancellationTokenSource = new CancellationTokenSource(); Worker = System.Threading.Tasks.Task.Factory.StartNew( () => RunTasks(_cancellationTokenSource.Token), _cancellationTokenSource.Token ); } private static void RunTasks(CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { Thread.Sleep(1000); // simulate work } } public void Stop() { try { _cancellationTokenSource.Cancel(); Worker.Wait(_cancellationTokenSource.Token); } catch (OperationCanceledException) { // OperationCanceledException is expected when a Task is cancelled. } } } When Stop() returns I expect Worker.Status to be TaskStatus.Canceled. My unit tests have shown that under certain conditions Worker.Status remains set to TaskStatus.Running. Is this a correct way to implement a cancellable worker thread?

    Read the article

  • Running a python script in background from a CGI

    - by Cagey
    I have a python CGI which runs some script in the background and shows the stdout in the html page. I run the script when the user clicks some button in the page. My problem is when the script starts running the page becomes busy and the user can't use the other client side features in the page. What I want is: The script should run in background when the user clicks the button and should notify the CGI when run is complete. Then the CGI show should the stdout of the script run. How can this be done?

    Read the article

  • Can a Heroku app add/remove dynos or workers to/from itself?

    - by Kiwi
    Heroku allows you to add and remove dynos and workers on the fly and charges you per second that each is used. Is it possible to set up my app so that it can add/remove dynos and workers from itself depending on the load it's under? This paragraph on Heroku.com mentions an API, but I can't find out much more about it.

    Read the article

  • Is Amazon SQS the right choice here? Rails performance issue.

    - by ole_berlin
    I'm close to releasing a rails app with the common networking features (messaging, wall, etc.). I want to use some kind of background processing (most likely Bj) for off-loading tasks from the request/response cycle. This would happen when users invite friends via email to join and for email notifications. I'm not sure if I should just drop these invites and notifications in my Database, using a model and then just process it with a worker process every x minutes or if I should go for Amazon SQS, storing the messages and invites there and let my worker retrieve it from Amazon SQS for processing (sending the invites / notifications). The Amazon approach would get load off my Database but I guess it is slower to retrieve messages from there. What do you think?

    Read the article

  • Smart Background Thread Task in Ruby on Rails?

    - by elado
    I need to perform a task every 5 seconds, but only when users are using the application. As for now, I use cron that works every minute and activates a task that repeats itself every 5 seconds with sleeps between, for a minute. However, it works also when the application isn't being used. Is there a gem that will do this kind of thing?

    Read the article

  • Invalid Cross-Thread Operations from BackgroundWorker2_RunWorkerCompleted in C#

    - by Jim Fell
    Hello. I'm getting an error that does not make sense. Cross-thread operation not valid: Control 'buttonOpenFile' accessed from a thread other than the thread it was created on. In my application, the UI thread fires off backgroundWorker1, which when almost complete fires off backgroundWorker2 and waits for it to complete. backgroundWorker1 waits for backgroundWorker2 to complete, before it completes. AutoResetEvent variables are used to flag when each of the workers complete. In backgroundWorker2_RunWorkerComplete a function is called that resets the form controls. It is in this ResetFormControls() function where the exception is thrown. I thought it was safe to modify form controls in the RunWorkerCompleted function. Both background workers are instantiated from the UI thread. Here is a greatly summarized version of what I am doing: AutoResetEvent evtProgrammingComplete_c = new AutoResetEvent(false); AutoResetEvent evtResetComplete_c = new AutoResetEvent(false); private void ResetFormControls() { toolStripProgressBar1.Enabled = false; toolStripProgressBar1.RightToLeftLayout = false; toolStripProgressBar1.Value = 0; buttonInit.Enabled = true; buttonOpenFile.Enabled = true; // Error occurs here. buttonProgram.Enabled = true; buttonAbort.Enabled = false; buttonReset.Enabled = true; checkBoxPeripheryModule.Enabled = true; checkBoxVerbose.Enabled = true; comboBoxComPort.Enabled = true; groupBoxToolSettings.Enabled = true; groupBoxNodeSettings.Enabled = true; } private void buttonProgram_Click(object sender, EventArgs e) { while (backgroundWorkerProgram.IsBusy) backgroundWorkerProgram.CancelAsync(); backgroundWorkerProgram.RunWorkerAsync(); } private void backgroundWorkerProgram_DoWork(object sender, DoWorkEventArgs e) { // Does a bunch of stuff... if (tProgramStat_c == eProgramStat_t.DONE) { tProgramStat_c = eProgramStat_t.RESETTING; while (backgroundWorkerReset.IsBusy) backgroundWorkerReset.CancelAsync(); backgroundWorkerReset.RunWorkerAsync(); evtResetComplete_c.WaitOne(LONG_ACK_WAIT * 2); if (tResetStat_c == eResetStat_t.COMPLETED) tProgramStat_c = eProgramStat_t.DONE; } } private void backgroundWorkerProgram_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { // Updates form to report complete. No problems here. evtProgrammingComplete_c.Set(); backgroundWorkerProgram.Dispose(); } private void backgroundWorkerReset_DoWork(object sender, DoWorkEventArgs e) { // Does a bunch of stuff... if (tResetStat_c == eResetStat_t.COMPLETED) if (tProgramStat_c == eProgramStat_t.RESETTING) evtProgrammingComplete_c.WaitOne(); } private void backgroundWorkerReset_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { CloseAllComms(); ResetFormControls(); evtResetComplete_c.Set(); backgroundWorkerReset.Dispose(); } Any thoughts or suggestions you may have would be appreciated. I am using Microsoft Visual C# 2008 Express Edition. Thanks.

    Read the article

  • Background Worker Check For When It's Midnight?

    - by Soo
    I want to create a background worker for a WinForm that triggers code whenever midnight rolls by. I have an idea of how to do it, but I'm pretty sure it's not the best way to do it. while(1==1) { //if Datetime.Now == midnight, execute code //sleep(1second) }

    Read the article

  • VB.net avoiding cross thread exception with extension method

    - by user574632
    Hello I am trying to implement a solution for updating form controls without using a delegate. I am attempting to use the 1st solution on this page: http://www.dreamincode.net/forums/blog/143/entry-2337-handling-the-dreaded-cross-thread-exception/ Imports System.ComponentModel Imports System.Runtime.CompilerServices Public Module MyInvoke <Extension()> _ Public Sub CustomInvoke(Of T As ISynchronizeInvoke)(ByVal control As T, ByVal toPerform As Action(Of T)) If control.InvokeRequired Then control.Invoke(toPerform, New Object() {control}) toPerform(control) End If End Sub End Module The site gives this as example of how to use: Label1.CustomInvoke(l => l.Text = "Hello World!") But i get 'l' is not declared error. As you can see im very new to VB or any OOP. I can get the second solution on that page to work (using delegates) but i have quite a few things to do in this thread and it seems like i would need to write a new delegate sub for each thing, which seems wasteful. What i need to do is select the 1st item from a combobox, update a textbox.text with the selected item, and pass the selected item to a function. Then wait for x seconds and start again, selecting the second item. I can get it to work in a single threaded application, but i need the interface to remain responsive. Any help greatly appreciated. EDIT: OK so changing the syntax worked for the example. However if i change it from Label1.CustomInvoke(Sub(l) l.text = "hello world!") (which worked just fine) to: Dim indexnumber As Integer = 0 ComboBox1.CustomInvoke(Sub(l) l.SelectedIndex = indexnumber) I get a cross threading error as though i didnt even use this method: Cross-thread operation not valid: Control 'ComboBox1' accessed from a thread other than the thread it was created on. So now im back to where i started? Any further help very much appreciated.

    Read the article

  • File.Exists() returns false, but not in debug

    - by Tor Haugen
    I'm being completely confused here folks, My code throws an exception because File.Exists() returns false public override sealed TCargo ReadFile(string fileName) { if (!File.Exists(fileName)) { throw new ArgumentException("Provided file name does not exist", "fileName"); } Visual studio breaks at the throw statement, and I immediately check the value of File.Exists(fileName) in the immediate window. It returns true. When I drag the breakpoint back up to the if statement and execute it again, it throws again. fileName is an absolute path to a file. I'm not creating the file, nor writing to it (it's there all along). If I paste the path into the open dialog in Notepad, it reads the file without problems. The code is executing in a background worker. It's the only complicating factor I can think of. I am positive the file has not been opened already, either in the worker thread or elsewhere. What's going on here?

    Read the article

  • C# WinForms populating TreeView from List<myObj>

    - by user743354
    I have this structure of classes: public class L3Message { public int Number { get; set; } public string MessageName { get; set; } public string Device { get; set; } public string Time { get; set; } public string ScramblingCode { get; set; } public List<Parameter> Parameters { get; set; } public L3Message() { Parameters = new List<Parameter>(); } } public class Parameter { public int numOfWhitespaces { get; set; } public string ParameterName { get; set; } public string ParameterValue { get; set; } public Parameter Parent { get; set; } public List<Parameter> SubParameters { get; set; } public Parameter() { SubParameters = new List<Parameter>(); } } So, as return type from one of my Methods I have List of L3Messages (List < L3Message ), and I need to map that to TreeView in WinForms (populate TreeView from that List). If possible, I would like to that in separate thread. How can I achieve that?

    Read the article

  • background worker window controls not rendered

    - by senthil
    Is there any way to load window inside the background worker thread without using showdialog()? the background worker only terminate only after getting some input from the window. Here the issue is window shown but the button and other controls are not rendered even we don't have control over any of the window.

    Read the article

  • Rerunning DoWork on Background Worker Based on Result?

    - by Soo
    Let's say I have a backgroundWorker1_DoWork that finds a value in a database and returns it in e.Result. Let's say I also have a backgroundWorker1_RunWorkerCompleted that reads the result. What I want to be able to do is based on e.Result, I can re-run backgroundWorker1_DoWork, and this I am not sure how to do. I'd really appreciate any help.

    Read the article

  • PHP: Prevent a function from returning value?

    - by Industrial
    Hi everybody, How could I make sure that the startProcess(); function is being called, but without halting the execution for myFunction(). I'll guess that there's a way to call a function and prevent it from returning it's value to thereby accomplishing this? Pseudo-code: function myFunction() { startProcess(); return $something; } function startProcess() { sleep(5); // Do stuff that user doesn't should have to wait for. }

    Read the article

  • How do I reference a control in a different thread?

    - by Testifier
    //button is clicked //worker starts private void processWorker_DoWork(object sender, DoWorkEventArgs e) { string code = DoLongWorkAndReturnCode(); if (code != 0) { MessageBox.Show("Error!"); EnableAllButtons(); // this is defined in the other thread and it's where i run into the error. } else { string code = DoAnotherLongProcessAndReturnCode(); if (code != 0) { MessageBox.Show("Error 2!"); EnableAllButtons(); // again, this is defined in the other thread } } } I'm running into a cross threading error because "EnableAllButtons()" is defined in a different thread. How do I go about enabling all buttons in one thread, from a different thread?

    Read the article

  • .NET threading solution for long queries

    - by Eddie
    Senerio We have an application that records incidents. An external database needs to be queried when an incident is approved by a supervisor. The queries to this external database are sometimes taking a while to run. This lag is experienced through the browser. Possible Solution I want to use threading to eliminate the simulated hang to the browser. I have used the Thread class before and heard about ThreadPool. But, I just found BackgroundWorker in this post. MSDN states: The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution. Is BackgroundWorker the way to go when handling long running queries? What happens when 2 or more BackgroundWorker processes are ran simultaneously? Is it handled like a pool?

    Read the article

  • Handling scroll event on listview in c#

    - by murasaki5
    I have a listview that generates thumbnail using a backgroundworker. When the listview is being scrolled i want to pause the backgroundworker and get the current value of the scrolled area, when the user stopped scrolling the listview, resume the backgroundworker starting from the item according to the value of the scrolled area. Is it possible to handle scroll event of a listview? if yes how? if not then what is a good alternative according to what i described above?

    Read the article

  • C# threading solution for long queries

    - by Eddie
    Senerio We have an application that records incidents. An external database needs to be queried when an incident is approved by a supervisor. The queries to this external database are sometimes taking a while to run. This lag is experienced through the browser. Possible Solution I want to use threading to eliminate the simulated hang to the browser. I have used the Thread class before and heard about ThreadPool. But, I just found BackgroundWorker in this post. MSDN states: The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution. Is BackgroundWorker the way to go when handling long running queries? What happens when 2 or more BackgroundWorker processes are ran simultaneously? Is it handled like a pool?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8  | Next Page >