Search Results

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

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

  • How do I run asynchronous code in asp.net mvc 2?

    - by SLC
    I tried this: BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += (o, e) => { SendConfEmail(); }; bw.RunWorkerAsync(); but it didn't work. SendConfEmail takes a while to run. I guess it's because BackgroundWorker is designed for winforms not webforms. Any ideas how I can solve the problem?

    Read the article

  • Why you need to learn async in .NET

    - by PSteele
    I had an opportunity to teach a quick class yesterday about what’s new in .NET 4.0.  One of the topics was the TPL (Task Parallel Library) and how it can make async programming easier.  I also stressed that this is the direction Microsoft is going with for C# 5.0 and learning the TPL will greatly benefit their understanding of the new async stuff.  We had a little time left over and I was able to show some code that uses the Async CTP to accomplish some stuff, but it wasn’t a simple demo that you could jump in to and understand so I thought I’d thrown one together and put it in a blog post. The entire solution file with all of the sample projects is located here. A Simple Example Let’s start with a super-simple example (WindowsApplication01 in the solution). I’ve got a form that displays a label and a button.  When the user clicks the button, I want to start displaying the current time for 15 seconds and then stop. What I’d like to write is this: lblTime.ForeColor = Color.Red; for (var x = 0; x < 15; x++) { lblTime.Text = DateTime.Now.ToString("HH:mm:ss"); Thread.Sleep(1000); } lblTime.ForeColor = SystemColors.ControlText; (Note that I also changed the label’s color while counting – not quite an ILM-level effect, but it adds something to the demo!) As I’m sure most of my readers are aware, you can’t write WinForms code this way.  WinForms apps, by default, only have one thread running and it’s main job is to process messages from the windows message pump (for a more thorough explanation, see my Visual Studio Magazine article on multithreading in WinForms).  If you put a Thread.Sleep in the middle of that code, your UI will be locked up and unresponsive for those 15 seconds.  Not a good UX and something that needs to be fixed.  Sure, I could throw an “Application.DoEvents()” in there, but that’s hacky. The Windows Timer Then I think, “I can solve that.  I’ll use the Windows Timer to handle the timing in the background and simply notify me when the time has changed”.  Let’s see how I could accomplish this with a Windows timer (WindowsApplication02 in the solution): public partial class Form1 : Form { private readonly Timer clockTimer; private int counter;   public Form1() { InitializeComponent(); clockTimer = new Timer {Interval = 1000}; clockTimer.Tick += UpdateLabel; }   private void UpdateLabel(object sender, EventArgs e) { lblTime.Text = DateTime.Now.ToString("HH:mm:ss"); counter++; if (counter == 15) { clockTimer.Enabled = false; lblTime.ForeColor = SystemColors.ControlText; } }   private void cmdStart_Click(object sender, EventArgs e) { lblTime.ForeColor = Color.Red; counter = 0; clockTimer.Start(); } } Holy cow – things got pretty complicated here.  I use the timer to fire off a Tick event every second.  Inside there, I can update the label.  Granted, I can’t use a simple for/loop and have to maintain a global counter for the number of iterations.  And my “end” code (when the loop is finished) is now buried inside the bottom of the Tick event (inside an “if” statement).  I do, however, get a responsive application that doesn’t hang or stop repainting while the 15 seconds are ticking away. But doesn’t .NET have something that makes background processing easier? The BackgroundWorker Next I try .NET’s BackgroundWorker component – it’s specifically designed to do processing in a background thread (leaving the UI thread free to process the windows message pump) and allows updates to be performed on the main UI thread (WindowsApplication03 in the solution): public partial class Form1 : Form { private readonly BackgroundWorker worker;   public Form1() { InitializeComponent(); worker = new BackgroundWorker {WorkerReportsProgress = true}; worker.DoWork += StartUpdating; worker.ProgressChanged += UpdateLabel; worker.RunWorkerCompleted += ResetLabelColor; }   private void StartUpdating(object sender, DoWorkEventArgs e) { var workerObject = (BackgroundWorker) sender; for (int x = 0; x < 15; x++) { workerObject.ReportProgress(0); Thread.Sleep(1000); } }   private void UpdateLabel(object sender, ProgressChangedEventArgs e) { lblTime.Text = DateTime.Now.ToString("HH:mm:ss"); }   private void ResetLabelColor(object sender, RunWorkerCompletedEventArgs e) { lblTime.ForeColor = SystemColors.ControlText; }   private void cmdStart_Click(object sender, EventArgs e) { lblTime.ForeColor = Color.Red; worker.RunWorkerAsync(); } } Well, this got a little better (I think).  At least I now have my simple for/next loop back.  Unfortunately, I’m still dealing with event handlers spread throughout my code to co-ordinate all of this stuff in the right order. Time to look into the future. The async way Using the Async CTP, I can go back to much simpler code (WindowsApplication04 in the solution): private async void cmdStart_Click(object sender, EventArgs e) { lblTime.ForeColor = Color.Red; for (var x = 0; x < 15; x++) { lblTime.Text = DateTime.Now.ToString("HH:mm:ss"); await TaskEx.Delay(1000); } lblTime.ForeColor = SystemColors.ControlText; } This code will run just like the Timer or BackgroundWorker versions – fully responsive during the updates – yet is way easier to implement.  In fact, it’s almost a line-for-line copy of the original version of this code.  All of the async plumbing is handled by the compiler and the framework.  My code goes back to representing the “what” of what I want to do, not the “how”. I urge you to download the Async CTP.  All you need is .NET 4.0 and Visual Studio 2010 sp1 – no need to set up a virtual machine with the VS2011 beta (unless, of course, you want to dive right in to the C# 5.0 stuff!).  Starting playing around with this today and see how much easier it will be in the future to write async-enabled applications.

    Read the article

  • What is the simplest way to implement multithreading in c# to existing code

    - by Kaeso
    I have already implemented a functionnal application that parses 26 pages of html all at once to produce an xml file with data contained on the web pages. I would need to implement a thread so that this method can work in the background without causing my app to seems unresponsive. Secondly, I have another function that is decoupled from the first one which compares two xml files to produce a third one and then transform this third xml file to produce an html page using XSLT. This would have to be on a thread, where I can click Cancel to stop the thread whithout crashing the app. What is the easiest best way to do this using WPF forms in VS 2010 ? I have chosen to use the BackgroundWorker. BackgroundWorker implementation: public partial class MainWindow : Window { private BackgroundWorker bw = new BackgroundWorker(); public MainWindow() { InitializeComponent(); bw.WorkerReportsProgress = true; bw.DoWork += new DoWorkEventHandler(bw_DoWork); bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted); } private void Window_Loaded(object sender, RoutedEventArgs e) { this.LoadFiles(); } private void btnCompare_Click(object sender, EventArgs e) { if (bw.IsBusy != true) { progressBar2.IsIndeterminate = true; // Start the asynchronous operation. bw.RunWorkerAsync(); } } private void bw_DoWork(object sender, DoWorkEventArgs e) { StatsProcessor proc = new StatsProcessor(); if (lstStatsBox1.SelectedItem != null) if (lstStatsBox2.SelectedItem != null) proc.CompareStats(lstStatsBox1.SelectedItem.ToString(), lstStatsBox2.SelectedItem.ToString()); } private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { progressBar2.IsIndeterminate = false; progressBar2.Value = 100; } I have started with the bgworker solution, but it seems that the bw_DoWork method is never called when btnCompare is clicked, I must be doing something wrong... I am new to threads.

    Read the article

  • Windows Azure Service Bus Scatter-Gather Implementation

    - by Alan Smith
    One of the more challenging enterprise integration patterns that developers may wish to implement is the Scatter-Gather pattern. In this article I will show the basic implementation of a scatter-gather pattern using the topic-subscription model of the windows azure service bus. I’ll be using the implementation in demos, and also as a lab in my training courses, and the pattern will also be included in the next release of my free e-book the “Windows Azure Service Bus Developer Guide”. The Scatter-Gather pattern answers the following scenario. How do you maintain the overall message flow when a message needs to be sent to multiple recipients, each of which may send a reply? Use a Scatter-Gather that broadcasts a message to multiple recipients and re-aggregates the responses back into a single message. The Enterprise Integration Patterns website provides a description of the Scatter-Gather pattern here.   The scatter-gather pattern uses a composite of the publish-subscribe channel pattern and the aggregator pattern. The publish-subscribe channel is used to broadcast messages to a number of receivers, and the aggregator is used to gather the response messages and aggregate them together to form a single message. Scatter-Gather Scenario The scenario for this scatter-gather implementation is an application that allows users to answer questions in a poll based voting scenario. A poll manager application will be used to broadcast questions to users, the users will use a voting application that will receive and display the questions and send the votes back to the poll manager. The poll manager application will receive the users’ votes and aggregate them together to display the results. The scenario should be able to scale to support a large number of users.   Scatter-Gather Implementation The diagram below shows the overall architecture for the scatter-gather implementation.       Messaging Entities Looking at the scatter-gather pattern diagram it can be seen that the topic-subscription architecture is well suited for broadcasting a message to a number of subscribers. The poll manager application can send the question messages to a topic, and each voting application can receive the question message on its own subscription. The static limit of 2,000 subscriptions per topic in the current release means that 2,000 voting applications can receive question messages and take part in voting. The vote messages can then be sent to the poll manager application using a queue. The voting applications will send their vote messages to the queue, and the poll manager will receive and process the vote messages. The questions topic and answer queue are created using the Windows Azure Developer Portal. Each instance of the voting application will create its own subscription in the questions topic when it starts, allowing the question messages to be broadcast to all subscribing voting applications. Data Contracts Two simple data contracts will be used to serialize the questions and votes as brokered messages. The code for these is shown below.   [DataContract] public class Question {     [DataMember]     public string QuestionText { get; set; } }     To keep the implementation of the voting functionality simple and focus on the pattern implementation, the users can only vote yes or no to the questions.   [DataContract] public class Vote {     [DataMember]     public string QuestionText { get; set; }       [DataMember]     public bool IsYes { get; set; } }     Poll Manager Application The poll manager application has been implemented as a simple WPF application; the user interface is shown below. A question can be entered in the text box, and sent to the topic by clicking the Add button. The topic and subscriptions used for broadcasting the messages are shown in a TreeView control. The questions that have been broadcast and the resulting votes are shown in a ListView control. When the application is started any existing subscriptions are cleared form the topic, clients are then created for the questions topic and votes queue, along with background workers for receiving and processing the vote messages, and updating the display of subscriptions.   public MainWindow() {     InitializeComponent();       // Create a new results list and data bind it.     Results = new ObservableCollection<Result>();     lsvResults.ItemsSource = Results;       // Create a token provider with the relevant credentials.     TokenProvider credentials =         TokenProvider.CreateSharedSecretTokenProvider         (AccountDetails.Name, AccountDetails.Key);       // Create a URI for the serivce bus.     Uri serviceBusUri = ServiceBusEnvironment.CreateServiceUri         ("sb", AccountDetails.Namespace, string.Empty);       // Clear out any old subscriptions.     NamespaceManager = new NamespaceManager(serviceBusUri, credentials);     IEnumerable<SubscriptionDescription> subs =         NamespaceManager.GetSubscriptions(AccountDetails.ScatterGatherTopic);     foreach (SubscriptionDescription sub in subs)     {         NamespaceManager.DeleteSubscription(sub.TopicPath, sub.Name);     }       // Create the MessagingFactory     MessagingFactory factory = MessagingFactory.Create(serviceBusUri, credentials);       // Create the topic and queue clients.     ScatterGatherTopicClient =         factory.CreateTopicClient(AccountDetails.ScatterGatherTopic);     ScatterGatherQueueClient =         factory.CreateQueueClient(AccountDetails.ScatterGatherQueue);       // Start the background worker threads.     VotesBackgroundWorker = new BackgroundWorker();     VotesBackgroundWorker.DoWork += new DoWorkEventHandler(ReceiveMessages);     VotesBackgroundWorker.RunWorkerAsync();       SubscriptionsBackgroundWorker = new BackgroundWorker();     SubscriptionsBackgroundWorker.DoWork += new DoWorkEventHandler(UpdateSubscriptions);     SubscriptionsBackgroundWorker.RunWorkerAsync(); }     When the poll manager user nters a question in the text box and clicks the Add button a question message is created and sent to the topic. This message will be broadcast to all the subscribing voting applications. An instance of the Result class is also created to keep track of the votes cast, this is then added to an observable collection named Results, which is data-bound to the ListView control.   private void btnAddQuestion_Click(object sender, RoutedEventArgs e) {     // Create a new result for recording votes.     Result result = new Result()     {         Question = txtQuestion.Text     };     Results.Add(result);       // Send the question to the topic     Question question = new Question()     {         QuestionText = result.Question     };     BrokeredMessage msg = new BrokeredMessage(question);     ScatterGatherTopicClient.Send(msg);       txtQuestion.Text = ""; }     The Results class is implemented as follows.   public class Result : INotifyPropertyChanged {     public string Question { get; set; }       private int m_YesVotes;     private int m_NoVotes;       public event PropertyChangedEventHandler PropertyChanged;       public int YesVotes     {         get { return m_YesVotes; }         set         {             m_YesVotes = value;             NotifyPropertyChanged("YesVotes");         }     }       public int NoVotes     {         get { return m_NoVotes; }         set         {             m_NoVotes = value;             NotifyPropertyChanged("NoVotes");         }     }       private void NotifyPropertyChanged(string prop)     {         if(PropertyChanged != null)         {             PropertyChanged(this, new PropertyChangedEventArgs(prop));         }     } }     The INotifyPropertyChanged interface is implemented so that changes to the number of yes and no votes will be updated in the ListView control. Receiving the vote messages from the voting applications is done asynchronously, using a background worker thread.   // This runs on a background worker. private void ReceiveMessages(object sender, DoWorkEventArgs e) {     while (true)     {         // Receive a vote message from the queue         BrokeredMessage msg = ScatterGatherQueueClient.Receive();         if (msg != null)         {             // Deserialize the message.             Vote vote = msg.GetBody<Vote>();               // Update the results.             foreach (Result result in Results)             {                 if (result.Question.Equals(vote.QuestionText))                 {                     if (vote.IsYes)                     {                         result.YesVotes++;                     }                     else                     {                         result.NoVotes++;                     }                     break;                 }             }               // Mark the message as complete.             msg.Complete();         }       } }     When a vote message is received, the result that matches the vote question is updated with the vote from the user. The message is then marked as complete. A second background thread is used to update the display of subscriptions in the TreeView, with a dispatcher used to update the user interface. // This runs on a background worker. private void UpdateSubscriptions(object sender, DoWorkEventArgs e) {     while (true)     {         // Get a list of subscriptions.         IEnumerable<SubscriptionDescription> subscriptions =             NamespaceManager.GetSubscriptions(AccountDetails.ScatterGatherTopic);           // Update the user interface.         SimpleDelegate setQuestion = delegate()         {             trvSubscriptions.Items.Clear();             TreeViewItem topicItem = new TreeViewItem()             {                 Header = AccountDetails.ScatterGatherTopic             };               foreach (SubscriptionDescription subscription in subscriptions)             {                 TreeViewItem subscriptionItem = new TreeViewItem()                 {                     Header = subscription.Name                 };                 topicItem.Items.Add(subscriptionItem);             }             trvSubscriptions.Items.Add(topicItem);               topicItem.ExpandSubtree();         };         this.Dispatcher.BeginInvoke(DispatcherPriority.Send, setQuestion);           Thread.Sleep(3000);     } }       Voting Application The voting application is implemented as another WPF application. This one is more basic, and allows the user to vote “Yes” or “No” for the questions sent by the poll manager application. The user interface for that application is shown below. When an instance of the voting application is created it will create a subscription in the questions topic using a GUID as the subscription name. The application can then receive copies of every question message that is sent to the topic. Clients for the new subscription and the votes queue are created, along with a background worker to receive the question messages. The voting application is set to receiving mode, meaning it is ready to receive a question message from the subscription.   public MainWindow() {     InitializeComponent();       // Set the mode to receiving.     IsReceiving = true;       // Create a token provider with the relevant credentials.     TokenProvider credentials =         TokenProvider.CreateSharedSecretTokenProvider         (AccountDetails.Name, AccountDetails.Key);       // Create a URI for the serivce bus.     Uri serviceBusUri = ServiceBusEnvironment.CreateServiceUri         ("sb", AccountDetails.Namespace, string.Empty);       // Create the MessagingFactory     MessagingFactory factory = MessagingFactory.Create(serviceBusUri, credentials);       // Create a subcription for this instance     NamespaceManager mgr = new NamespaceManager(serviceBusUri, credentials);     string subscriptionName = Guid.NewGuid().ToString();     mgr.CreateSubscription(AccountDetails.ScatterGatherTopic, subscriptionName);       // Create the subscription and queue clients.     ScatterGatherSubscriptionClient = factory.CreateSubscriptionClient         (AccountDetails.ScatterGatherTopic, subscriptionName);     ScatterGatherQueueClient =         factory.CreateQueueClient(AccountDetails.ScatterGatherQueue);       // Start the background worker thread.     BackgroundWorker = new BackgroundWorker();     BackgroundWorker.DoWork += new DoWorkEventHandler(ReceiveMessages);     BackgroundWorker.RunWorkerAsync(); }     I took the inspiration for creating the subscriptions in the voting application from the chat application that uses topics and subscriptions blogged by Ovais Akhter here. The method that receives the question messages runs on a background thread. If the application is in receive mode, a question message will be received from the subscription, the question will be displayed in the user interface, the voting buttons enabled, and IsReceiving set to false to prevent more questing from being received before the current one is answered.   // This runs on a background worker. private void ReceiveMessages(object sender, DoWorkEventArgs e) {     while (true)     {         if (IsReceiving)         {             // Receive a question message from the topic.             BrokeredMessage msg = ScatterGatherSubscriptionClient.Receive();             if (msg != null)             {                 // Deserialize the message.                 Question question = msg.GetBody<Question>();                   // Update the user interface.                 SimpleDelegate setQuestion = delegate()                 {                     lblQuestion.Content = question.QuestionText;                     btnYes.IsEnabled = true;                     btnNo.IsEnabled = true;                 };                 this.Dispatcher.BeginInvoke(DispatcherPriority.Send, setQuestion);                 IsReceiving = false;                   // Mark the message as complete.                 msg.Complete();             }         }         else         {             Thread.Sleep(1000);         }     } }     When the user clicks on the Yes or No button, the btnVote_Click method is called. This will create a new Vote data contract with the appropriate question and answer and send the message to the poll manager application using the votes queue. The user voting buttons are then disabled, the question text cleared, and the IsReceiving flag set to true to allow a new message to be received.   private void btnVote_Click(object sender, RoutedEventArgs e) {     // Create a new vote.     Vote vote = new Vote()     {         QuestionText = (string)lblQuestion.Content,         IsYes = ((sender as Button).Content as string).Equals("Yes")     };       // Send the vote message.     BrokeredMessage msg = new BrokeredMessage(vote);     ScatterGatherQueueClient.Send(msg);       // Update the user interface.     lblQuestion.Content = "";     btnYes.IsEnabled = false;     btnNo.IsEnabled = false;     IsReceiving = true; }     Testing the Application In order to test the application, an instance of the poll manager application is started; the user interface is shown below. As no instances of the voting application have been created there are no subscriptions present in the topic. When an instance of the voting application is created the subscription will be displayed in the poll manager. Now that a voting application is subscribing, a questing can be sent from the poll manager application. When the message is sent to the topic, the voting application will receive the message and display the question. The voter can then answer the question by clicking on the appropriate button. The results of the vote are updated in the poll manager application. When two more instances of the voting application are created, the poll manager will display the new subscriptions. More questions can then be broadcast to the voting applications. As the question messages are queued up in the subscription for each voting application, the users can answer the questions in their own time. The vote messages will be received by the poll manager application and aggregated to display the results. The screenshots of the applications part way through voting are shown below. The messages for each voting application are queued up in sequence on the voting application subscriptions, allowing the questions to be answered at different speeds by the voters.

    Read the article

  • Is it possible to have CommandManager requery only specific WPF command instead of all?

    - by aoven
    I'm trying to implement a highly responsive UI for my MVVM application, so I've chosen to have all command handlers automatically execute in a BackgroundWorker so they don't block the UI. But at the same time, I don't want the user to be able to execute the same command while it is still executing in the background. The solution seems obvious: When Executed handler is invoked, have the CanExecute handler return false Start the BackgroundWorker async When BackgroundWorker finishes, have the CanExecute handler return true again. Problem is, I need to notify WPF after step 1 and again after step 3 that CanExecute has changed and that it should be required. I know I can do it by calling CommandManager.InvalidateRequerySuggested, but that causes CanExecute handlers of all other commands to be requeried as well. Having a lot of commands, that's not good. Is there a way to ask for requery of a specific command - i.e. the one that is currently being executed? TIA

    Read the article

  • 10000's+ UI elements, bind or draw?

    - by jpiccolo
    I am drawing a header for a timeline control. It looks like this: I go to 0.01 millisecond per line, so for a 10 minute timeline I am looking at drawing 60000 lines + 6000 labels. This takes a while, ~10 seconds. I would like to offload this from the UI thread. My code is currently: private void drawHeader() { Header.Children.Clear(); switch (viewLevel) { case ViewLevel.MilliSeconds100: double hWidth = Header.Width; this.drawHeaderLines(new TimeSpan(0, 0, 0, 0, 10), 100, 5, hWidth); //Was looking into background worker to off load UI //backgroundWorker = new BackgroundWorker(); //backgroundWorker.DoWork += delegate(object sender, DoWorkEventArgs args) // { // this.drawHeaderLines(new TimeSpan(0, 0, 0, 0, 10), 100, 5, hWidth); // }; //backgroundWorker.RunWorkerAsync(); break; } } private void drawHeaderLines(TimeSpan timeStep, int majorEveryXLine, int distanceBetweenLines, double headerWidth) { var currentTime = new TimeSpan(0, 0, 0, 0, 0); const int everyXLine100 = 10; double currentX = 0; var currentLine = 0; while (currentX < headerWidth) { var l = new Line { ToolTip = currentTime.ToString(@"hh\:mm\:ss\.fff"), StrokeThickness = 1, X1 = 0, X2 = 0, Y1 = 30, Y2 = 25 }; if (((currentLine % majorEveryXLine) == 0) && currentLine != 0) { l.StrokeThickness = 2; l.Y2 = 15; var textBlock = new TextBlock { Text = l.ToolTip.ToString(), FontSize = 8, FontFamily = new FontFamily("Tahoma"), Foreground = new SolidColorBrush(Color.FromRgb(255, 255, 255)) }; Canvas.SetLeft(textBlock, (currentX - 22)); Canvas.SetTop(textBlock, 0); Header.Children.Add(textBlock); } if ((((currentLine % everyXLine100) == 0) && currentLine != 0) && (currentLine % majorEveryXLine) != 0) { l.Y2 = 20; var textBlock = new TextBlock { Text = string.Format(".{0}", TimeSpan.Parse(l.ToolTip.ToString()).Milliseconds), FontSize = 8, FontFamily = new FontFamily("Tahoma"), Foreground = new SolidColorBrush(Color.FromRgb(192, 192, 192)) }; Canvas.SetLeft(textBlock, (currentX - 8)); Canvas.SetTop(textBlock, 8); Header.Children.Add(textBlock); } l.Stroke = new SolidColorBrush(Color.FromRgb(255, 255, 255)); Header.Children.Add(l); Canvas.SetLeft(l, currentX); currentX += distanceBetweenLines; currentLine++; currentTime += timeStep; } } I had looked into BackgroundWorker, except you can't create UI elements on a non-UI thread. Is it possible at all to do drawHeaderLines in a non-UI thread? Could I use data binding for drawing the lines? Would this help with UI responsiveness? I would imagine I can use databinding, but the Styling is probably beyond my current WPF ability (coming from winforms and trying to learn what all these style objects are and binding them). Would anyone be able to supply a starting point for tempting this out? Or Google a tutorial that would get me started?

    Read the article

  • Preventing ListBox scrolling to top when updated

    - by WDZ
    I'm trying to build a simple music player with a ListBox playlist. When adding audio files to the playlist, it first fills the ListBox with the filenames and then (on a separate thread) extracts the ID3 data and overwrites the filenames with the correct Artist - Title information (much like Winamp). But while the ListBox is being updated, it's unscrollable, as it always jumps to the top on every item overwrite. Any way to prevent this? EDIT: The code: public Form1() { //Some initialization code omitted here BindingList<TAG_INFO> trackList = new BindingList<TAG_INFO>(); // The Playlist this.playlist = new System.Windows.Forms.ListBox(); this.playlist.Location = new System.Drawing.Point(12, 12); this.playlist.Name = "playlist"; this.playlist.Size = new System.Drawing.Size(229, 316); this.playlist.DataSource = trackList; } private void playlist_add_Click(object sender, EventArgs e) { //Initialize OpenFileDialog OpenFileDialog opd = new OpenFileDialog(); opd.Filter = "Music (*.WAV; *.MP3; *.FLAC)|*.WAV;*.MP3;*.FLAC|All files (*.*)|*.*"; opd.Title = "Select Music"; opd.Multiselect = true; //Open OpenFileDialog if (DialogResult.OK == opd.ShowDialog()) { //Add opened files to playlist for (int i = 0; opd.FileNames.Length > i; ++i) { if (File.Exists(opd.FileNames[i])) { trackList.Add(new TAG_INFO(opd.FileNames[i])); } } //Initialize BackgroundWorker BackgroundWorker _bw = new BackgroundWorker(); _bw.WorkerReportsProgress = true; _bw.DoWork += new DoWorkEventHandler(thread_trackparser_DoWork); _bw.ProgressChanged += new ProgressChangedEventHandler(_bw_ProgressChanged); //Start ID3 extraction _bw.RunWorkerAsync(); } } void thread_trackparser_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker _bw = sender as BackgroundWorker; for (int i = 0; i < trackList.Count; ++i) { //Pass extracted tag info to _bw_ProgressChanged for thread-safe playlist entry update _bw.ReportProgress(0,new object[2] {i, BassTags.BASS_TAG_GetFromFile(trackList[i].filename)}); } } void _bw_ProgressChanged(object sender, ProgressChangedEventArgs e) { object[] unboxed = e.UserState as object[]; trackList[(int)unboxed[0]] = (unboxed[1] as TAG_INFO); } EDIT2: Much simpler test case: Try scrolling down without selecting an item. The changing ListBox will scroll to the top again. using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public class Form1 : Form { private System.ComponentModel.IContainer components = null; protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.listBox1 = new System.Windows.Forms.ListBox(); this.timer1 = new System.Windows.Forms.Timer(this.components); this.SuspendLayout(); // listBox1 this.listBox1.FormattingEnabled = true; this.listBox1.Location = new System.Drawing.Point(0, 0); this.listBox1.Name = "listBox1"; this.listBox1.Size = new System.Drawing.Size(200, 290); // timer1 this.timer1.Enabled = true; this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // Form1 this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(200, 290); this.Controls.Add(this.listBox1); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); } private System.Windows.Forms.ListBox listBox1; private System.Windows.Forms.Timer timer1; public Form1() { InitializeComponent(); for (int i = 0; i < 45; i++) listBox1.Items.Add(i); } int tickCounter = -1; private void timer1_Tick(object sender, EventArgs e) { if (++tickCounter > 44) tickCounter = 0; listBox1.Items[tickCounter] = ((int)listBox1.Items[tickCounter])+1; } } static class Program { [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }

    Read the article

  • WCF and ASP.NET - Server.Execute throwing object reference not set to an instance of an object

    - by user208662
    Hello, I have an ASP.NET page that calls to a WCF service. This WCF service uses a BackgroundWorker to asynchronously create an ASP.NET page on my server. Oddly, when I execute the WCF Service [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] public void PostRequest(string comments) { // Do stuff // If everything went o.k. asynchronously render a page on the server. I do not want to // block the caller while this is occurring. BackgroundWorker myWorker = new BackgroundWorker(); myWorker.DoWork += new DoWorkEventHandler(myWorker_DoWork); myWorker.RunWorkerAsync(HttpContext.Current); } private void myWorker_DoWork(object sender, DoWorkEventArgs e) { // Set the current context so we can render the page via Server.Execute HttpContext context = (HttpContext)(e.Argument); HttpContext.Current = context; // Retrieve the url to the page string applicationPath = context.Request.ApplicationPath; string sourceUrl = applicationPath + "/log.aspx"; string targetDirectory = currentContext.Server.MapPath("/logs/"); // Execute the other page and load its contents using (StringWriter stringWriter = new StringWriter()) { // Write the contents out to the target url // NOTE: THIS IS WHERE MY ERROR OCCURS currentContext.Server.Execute(sourceUrl, stringWriter); // Prepare to write out the result of the log targetPath = targetDirectory + "/" + DateTime.Now.ToShortDateString() + ".aspx"; using (StreamWriter streamWriter = new StreamWriter(targetPath, false)) { // Write out the content to the file sb.Append(stringWriter.ToString()); streamWriter.Write(sb.ToString()); } } } Oddly, when the currentContext.Server.Execute method is executed, it throws an "object reference not set to an instance of an object" error. The reason this is so strange is because I can look at the currentContext properties in the watch window. In addition, Server is not null. Because of this, I have no idea where this error is coming from. Can someone point me in the correct direction of what the cause of this could be? Thank you!

    Read the article

  • ASP.NET / WCF - Execute Server.Execute Asynchronously

    - by user208662
    Hello, I need to run the HttpContext.Current.Server.Execute method in my ASP.NET application. This application has a WCF operation that does some processing. Currently, I am to do my processing correctly from within my WCF operation. However, I would like to do this asynchronously. In an error to attempt this asynchronously, I tried running Server.Execute in the DoWork event handler of a BackgroundWorker. Unfortunately, this throws an error that says "object reference not set to an instance of an object" The HttpContext element is not null. I checked that. It is some property nested in the HttpContext object that appears to be null. However, I have not been able to identify why this won't work. It happens as soon as I move the processing to the BackgroundWorker thread. My question is, how can I asynchronously execute the Server.Execute method? Thank you,

    Read the article

  • C#: Two forms, one is calling the other one

    - by Shaza
    Hey all, I have a problem like this, I have two Winforms, f1 and f2. f1 will start a loop on button click, this loop checks a condition and decide to call the other form which is f2 or not. The problem is, the loop may call f2 many times, so each time the other form f2 will be called the first form f1 should pause its execution. So, I solved it like this, I used backgroundWorker + AutoResetEvent. I placed the backgroundWorker in the first form and inside the DoWork event handler I called f2.Show() then I called WaitOne on the AutoResetEvent let it be A. In the other form "f2", on Exiting button I called Set on the same A. But, unfortunately f2 got freezed when clicking that button in f1, what should I change??

    Read the article

  • Castle ActiveRecord: session error search and access to lazy loading property in different threads

    - by sc911
    Hi *, I've got a problem with an multi-threaded desktop application using Castle ActiveRecord in C#: To keep the GUI alive while searching for the objects based on userinput I'm using the BackgroundWorker for the search-function. Some of the properties of the objects, especially some HasMany-Relations, are marked as Lazy. Now, when the search is finished and the user selects an resulting object, some of the properties of this object should be displayed. But as the search was done by the BackgroundWorker in a different thread, accessing the properties fails as the session for the lazy-access is no longer available. What will be the best way to do the search in an extra thread to keep the GUI alive and to access all properties correctly including those marked as lazy? Thanks for any advise! Regards sc911

    Read the article

  • In C# or .NET, is there a way to prevent other threads from invoking methods on a particular thread?

    - by YWE
    I have a Windows Forms application with a BackgroundWorker. In a method on the main form, a MessageBox is shown and the user must click the OK button to continue. Meanwhile, while the messagebox is being displayed, the BackgroundWorker finishes executing and calls the RunWorkerCompleted event. In the method I have assigned to that event, which runs on the UI thread, the Close method is called on the form. Even though the method that shows the message box is still running, the UI thread is not blocking other threads from invoking methods on it. So the Close method gets called on the form. What I want is for the UI thread to block other threads' invokes until the method with the message box has finished. Is there an easy way to do that?

    Read the article

  • Asynchronously populate datagridview in Windows Forms application

    - by dcryptd
    howzit! I'm a web developer that has been recently requested to develop a Windows forms application, so please bear with me (or dont laugh!) if my question is a bit elementary. After many sessions with my client, we eventually decided on an interface that contains a tabcontrol with 5 tabs. Each tab has a datagridview that may eventually hold up to 25,000 rows of data (with about 6 columns each). I have successfully managed to bind the grids when the tab page is loaded and it works fine for a few records, but the UI freezes when I bound the grid with 20,000 dummy records. The "freeze" occurs when I click on the tab itself, and the UI only frees up (and the tab page is rendered) once the bind is complete. I communicated this to the client and mentioned the option of paging for each grid, but she is adament w.r.t. NOT wanting this. My only option then is to look for some asynchronous method of doing this in the background. I don't know much about threading in windows forms, but I know that I can use the BackgroundWorker control to achieve this. My only issue after reading up a bit on it is that it is ideally used for "long-running" tasks and I/O operations. My questions: How does one determine a long-running task? How does one NOT MISUSE the BackgroundWorker control, ie. is there a general guideline to follow when using this? (I understand that opening/spawning multiple threads may be undesirable in certain instances) Most importantly: How can I achieve (asychronously) binding of the datagridview after the tab page - and all its child controls - loads. Thank you for reading this (ahem) lengthy query, and I highly appreciate any responses/thoughts/directions on this matter! Cheers!

    Read the article

  • BitmapFrame in another thread

    - by Lasse Lindström
    Hi I am using a WPF BackgroundWorker to create thumbnails. My worker function looks like: private void work(object sender, DoWorkEventArgs e) { try { var paths = e.Argument as string[]; var boxList = new List(); foreach (string path in paths) { if (!string.IsNullOrEmpty(path)) { FileInfo info = new FileInfo(path); if (info.Exists && info.Length 0) { BitmapImage bi = new BitmapImage(); bi.BeginInit(); bi.DecodePixelWidth = 200; bi.CacheOption = BitmapCacheOption.OnLoad; bi.UriSource = new Uri(info.FullName); bi.EndInit(); var item = new BoxItem(); item.FilePath = path; MemoryStream ms = new MemoryStream(); PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bi)); encoder.Save(ms); item.ThumbNail = ms.ToArray(); ms.Close(); boxList.Add(item); } } } e.Result = boxList; } catch (Exception ex) { //nerver comes here } } When this fuction is finnished and before the BackgroundWorker "Completed" function is started, I can see on the output window on Vs2008, that a exception is generated. It looks like: A first chance exception of type 'System.NotSupportedException' occurred in PresentationCore.dll The number of exceptions generates equals the number of thumbnails to be generated. Using "trial and error" I have isolated the problem to: BitmapFrame.Create(bi) Removing that line (makes my function useless) also removes the exception. I have not found any explanation to this,,, or a better method to create thumbnails i a background thread. Can anyone help me? //lasse

    Read the article

  • Assigning a property across threads

    - by Mike
    I have set a property across threads before and I found this post http://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the-t about getting a property. I think my issue with the code below is setting the variable to the collection is an object therefore on the heap and therefore is just creating a pointer to the same object So my question is besides creating a deep copy, or copying the collection into a different List object is there a better way to do the following to aviod the error during the for loop. Cross-thread operation not valid: Control 'lstProcessFiles' accessed from a thread other than the thread it was created on. Code: private void btnRunProcess_Click(object sender, EventArgs e) { richTextBox1.Clear(); BackgroundWorker bg = new BackgroundWorker(); bg.DoWork += new DoWorkEventHandler(bg_DoWork); bg.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_RunWorkerCompleted); bg.RunWorkerAsync(lstProcessFiles.SelectedItems); } void bg_DoWork(object sender, DoWorkEventArgs e) { WorkflowEngine engine = new WorkflowEngine(); ListBox.SelectedObjectCollection selectedCollection=null; if (lstProcessFiles.InvokeRequired) { // Try #1 selectedCollection = (ListBox.SelectedObjectCollection) this.Invoke(new GetSelectedItemsDelegate(GetSelectedItems), new object[] { lstProcessFiles }); // Try #2 //lstProcessFiles.Invoke( // new MethodInvoker(delegate { // selectedCollection = lstProcessFiles.SelectedItems; })); } else { selectedCollection = lstProcessFiles.SelectedItems; } // *********Same Error on this line******************** // Cross-thread operation not valid: Control 'lstProcessFiles' accessed // from a thread other than the thread it was created on. foreach (string l in selectedCollection) { if (engine.LoadProcessDocument(String.Format(@"C:\TestDirectory\{0}", l))) { try { engine.Run(); WriteStep(String.Format("Ran {0} Succussfully", l)); } catch { WriteStep(String.Format("{0} Failed", l)); } engine.PrintProcess(); WriteStep(String.Format("Rrinted {0} to debug", l)); } } } private delegate void WriteDelegate(string p); private delegate ListBox.SelectedObjectCollection GetSelectedItemsDelegate(ListBox list); private ListBox.SelectedObjectCollection GetSelectedItems(ListBox list) { return list.SelectedItems; }

    Read the article

  • How to put large text data (~20mb) into sql cs 3.5 database?

    - by Anindya Chatterjee
    I am using following query to insert some large text data : internal static string InsertStorageItem = "insert into Storage(FolderName, MessageId, MessageDate, StorageData) values ('{0}', '{1}', '{2}', @StorageData)"; and the code I am using to execute this query is as follows : string content = "very very large data"; string query = string.Format(InsertStorageItem, "Inbox", "AXOGTRR1445/DSDS587444WEE", "4/19/2010 11:11:03 AM"); var command = new SqlCeCommand(query, _sqlConnection); var paramData = command.Parameters.Add("@StorageData", System.Data.SqlDbType.NText); paramData.Value = content; paramData.SourceColumn = "StorageData"; command.ExecuteNonQuery(); But at the last line I am getting this following error : System.Data.SqlServerCe.SqlCeException was unhandled by user code Message=The data was truncated while converting from one data type to another. [ Name of function(if known) = ] Source=SQL Server Compact ADO.NET Data Provider HResult=-2147467259 NativeError=25920 StackTrace: at System.Data.SqlServerCe.SqlCeCommand.ProcessResults(Int32 hr) at System.Data.SqlServerCe.SqlCeCommand.ExecuteCommandText(IntPtr& pCursor, Boolean& isBaseTableCursor) at System.Data.SqlServerCe.SqlCeCommand.ExecuteCommand(CommandBehavior behavior, String method, ResultSetOptions options) at System.Data.SqlServerCe.SqlCeCommand.ExecuteNonQuery() at Chithi.Client.Exchange.ExchangeClient.SaveItem(Item item, Folder parentFolder) at Chithi.Client.Exchange.ExchangeClient.DownloadNewMails(Folder folder) at Chithi.Client.Exchange.ExchangeClient.SynchronizeParentChildFolder(WellKnownFolder wellknownFolder, Folder parentFolder) at Chithi.Client.Exchange.ExchangeClient.SynchronizeFolders() at Chithi.Client.Exchange.ExchangeClient.WorkerThreadDoWork(Object sender, DoWorkEventArgs e) at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e) at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument) InnerException: Now my question is how am I supposed to insert such large data to sqlce db? Regards, Anindya Chatterjee http://abstractclass.org

    Read the article

  • Hang during databinding of large amount of data to WPF DataGrid

    - by nihi_l_ist
    Im using WPFToolkit datagrid control and do the binding in such way: <WpfToolkit:DataGrid x:Name="dgGeneral" SelectionMode="Single" SelectionUnit="FullRow" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" Grid.Row="1" ItemsSource="{Binding Path=Conversations}" > public List<CONVERSATION> Conversations { get { return conversations; } set { if (conversations != value) { conversations = value; NotifyPropertyChanged("Conversations"); } } } public event PropertyChangedEventHandler PropertyChanged; public void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } public void GenerateData() { BackgroundWorker bw = new BackgroundWorker(); bw.WorkerSupportsCancellation = bw.WorkerReportsProgress = true; List<CONVERSATION> list = new List<CONVERSATION>(); bw.DoWork += delegate { list = RefreshGeneralData(); }; bw.RunWorkerCompleted += delegate { try { Conversations = list; } catch (Exception ex) { CustomException.ExceptionLogCustomMessage(ex); } }; bw.RunWorkerAsync(); } And than in the main window i call GenerateData() after setting DataCotext of the window to instance of the class, containing GenerateData(). RefreshGeneralData() returns some list of data i want and it returns it fast. Overall there are near 2000 records and 6 columns(im not posting the code i used during grid's initialization, because i dont think it can be the reason) and the grid hangs for almost 10 secs!

    Read the article

  • wpf progress bar slows 10x times serial port communications... how could be possible that?

    - by D_Guidi
    I know that this could look a dumb question, but here's my problem. I have a worker dialog that "hides" a backgroundworker, so in a worker thread I do my job, I report the progress in a standard way and then I show the results in my WPF program. The dialog contains a simply animated gif and a standard wpf progress bar, and when a progress is notified I set Value property. All lokks as usual and works well for any kind of job, like web service calls, db queries, background elaboration and so on. For my job we use also many "couplers", card readers that reads data from smart card, that are managed with native C code that access to serial port (so, I don't use .NET SerialPort object). I have some nunit tests and I read a sample card in 10 seconds, but using my actual program, under the backgroundworker and showing my worker dialog, I need 1.30 minutes to do the SAME job. I struggled into problem for days until I decide to remove the worker dialog, and without dialog I obtain the same performances of the tests! So I investigated, and It's not the dialog, not the animated gif, but the wpf progress bar! Simply the fact that a progress bar is shown (so, no animation, no Value set called, nothing of nothing) slows serialport communicatitons. Looks incredible? I've tested this behavior and it's exactly what happens.

    Read the article

  • How To perform a SQL Query to DataTable Operation That Can Be Cancelled

    - by David W
    I tried to make the title as specific as possible. Basically what I have running inside a backgroundworker thread now is some code that looks like: SqlConnection conn = new SqlConnection(connstring); SqlCommand cmd = new SqlCommand(query, conn); conn.Open(); SqlDataAdapter sda = new SqlDataAdapter(cmd); sda.Fill(Results); conn.Close(); sda.Dispose(); Where query is a string representing a large, time consuming query, and conn is the connection object. My problem now is I need a stop button. I've come to realize killing the backgroundworker would be worthless because I still want to keep what results are left over after the query is canceled. Plus it wouldn't be able to check the canceled state until after the query. What I've come up with so far: I've been trying to conceptualize how to handle this efficiently without taking too big of a performance hit. My idea was to use a SqlDataReader to read the data from the query piece at a time so that I had a "loop" to check a flag I could set from the GUI via a button. The problem is as far as I know I can't use the Load() method of a datatable and still be able to cancel the sqlcommand. If I'm wrong please let me know because that would make cancelling slightly easier. In light of what I discovered I came to the realization I may only be able to cancel the sqlcommand mid-query if I did something like the below (pseudo-code): while(reader.Read()) { //check flag status //if it is set to 'kill' fire off the kill thread //otherwise populate the datatable with what was read } However, it would seem to me this would be highly ineffective and possibly costly. Is this the only way to kill a sqlcommand in progress that absolutely needs to be in a datatable? Any help would be appreciated!

    Read the article

  • Extra NotifyIcon shown in system tray

    - by Kettch19
    I'm having an issue with an app where my NotifyIcon displays an extra icon. The steps to reproduce it are easy, but the problem is that the extra icon shows up after any of the actual codebehind we've added fires. Put simply, clicking a button triggers execution of method FooBar() which runs all the way through fine but its primary duty is to fire a backgroundworker to log into another of our apps. It only appears if this particular button is clicked. Strangely enough, we have a WndProc method override and if I step through until the extra NotifyIcon appears, it always appears during this method so something else beyond the codebehind must be triggering the behavior. Our WndProc method is currently (although I don't think it's caused by the WndProc): Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message) 'Check for WM_COPYDATA message from other app or drag/drop action and handle message If m.Msg = NativeMethods.WM_COPYDATA Then ' get the standard message structure from lparam Dim CD As NativeMethods.COPYDATASTRUCT = m.GetLParam(GetType(NativeMethods.COPYDATASTRUCT)) 'setup byte array Dim B(CD.cbData) As Byte 'copy data from memory into array Runtime.InteropServices.Marshal.Copy(New IntPtr(CD.lpData), B, 0, CD.cbData) 'Get message as string and process ProcessWMCopyData(System.Text.Encoding.Default.GetString(B)) 'empty array Erase B 'set message result to 'true', meaning message handled m.Result = New IntPtr(1) End If 'pass on result and all messages not handled by this app MyBase.WndProc(m) End Sub The only place in the code where the NotifyIcon in question is manipulated at all is in the following event handler (again, don't think this is the culprit, but just for more info): Private Sub TrayIcon_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles TrayIcon.MouseDoubleClick If Me.Visible Then Me.Hide() Else PositionBottomRight() Me.Show() End If End Sub The backgroundworker's DoWork is as follows (just a class call to log in to our other app, but again just for info): Private Sub LoginBackgroundWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles LoginBackgroundWorker.DoWork Settings.IsLoggedIn = _wdService.LogOn(Settings.UserName, Settings.Password) End Sub Does anyone else have ideas on what might be causing this or how to possibly further debug this? I've been banging my head on this without seeing a pattern so another set of eyes would be extremely appreciated. :) I've posted this on MSDN winforms forums as well and have had no luck there so far either.

    Read the article

  • Basic Application Organization + Publishing (.NET 4.0)

    - by keynesiancross
    Hi all, I'm trying to figure out the best way to keep my program organized. Currently I have many class files in one project file, but some of these classes do things that are very different, and some I would like to expose to other applications in the future. One thought I had to organizing my application was to create multiple project files, with one "Main" project, which would interact with all the other projects and their relevant classes as needed. Does this make sense? I was wondering if anyone had any suggestions in regards to using multiple project files in one solution (and how do you create something like this?), and if it makes sense to have multiple namespaces in one solution... Cheers ----Edit Below---- Sorry, my fault. Currently my program is all in one console project. Within this project I have several classes, some of which basically launch a BackgroundWorker and run an endless loop pulling data. The BackgroundWorker then passes this data back to the main business logic as needed. I'm hoping to seperate this data pull material (including the background worker material) into one project file, and the rest of the business logic into another project file. The projects will have to pass objects between eachother though (the data to the main business logic, and the business logic will pass startup parameteres to the dataPull project)... Hopefully this adds a bit more detail.

    Read the article

  • Winforms-how do I keep window fully painted/responsive during a long running synchronous request is

    - by Greg
    Hi, Background - For a winforms 3.5 c# application, I would like to keep the main window fully painted/responsive during a long running synchronous request. For example if the user moves the window. Question - Is there a way to achive this WITHOUT having to setup a separate thread or backgroundworker process? (e.g. like a way to call from within my long running transaction, "release a bit of CPU to mainform", at some points) thanks

    Read the article

  • WPF: Disable ListBox, but enable scrolling

    - by Matt Briggs
    Been banging my head against this all morning. Basically, I have a listbox, and I want to keep people from changing the selection during a long running process, but allow them to still scroll. Solution: All the answers were good, I went with swallowing mouse events since that was the most straight forward. I wired PreviewMouseDown and PreviewMouseUp to a single event, which checked my backgroundWorker.IsBusy, and if it was set the IsHandled property on the event args to true.

    Read the article

  • Download multiple files from an array C#

    - by Sandeep Bansal
    Hi everyone, I have an array of file names which I want to download. The array is currently contained in a string[] and it is working inside of a BackgroundWorker. What I want to do is use that array to download files and output the result into a progress bar which will tell me how long I have left for completion. Is there a way I can do this. Thanks.

    Read the article

  • C# - Extract Zip with file listing

    - by fonix232
    I would like to extract a pre-set zip file WITHOUT an external library to a given folder, and I would like to inform the user about the current percent of extraction (with a simple progressBar and a percent label) and the currently extracted file. Is this possible somehow? It is important to do not use any other library. (For updating all the labels and progressBar, I use a separate backgroundWorker)

    Read the article

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