Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
       {
           int count = (int)e.Argument;
           int sum = 0;
         
 
           for (int i = 0, j = 0; i < listView1.Items.Count && j < listView1.Items.Count; j++)
           {
               if (j != 0)
               {
                   listView1.Items[j - 1].Selected = false; //<big>ERRORR</big>
               }
 
               listView1.Items[j].Selected = true; //<big>ERROR</big>               
               Thread.Sleep(2000);
               if (backgroundWorker1.CancellationPending)
               {
                   e.Cancel = true;
                   break;
               }
 

               sum += i;
               backgroundWorker1.ReportProgress(i*100/count);
               Thread.Sleep(2000);
           }
 
           e.Result = sum;
       }
 

Any one Please Rectify this Error.
Posted 17-Aug-12 23:20pm

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

The cause of this error is that the backgroundworker runs in its own thread. Your UI including the listView1 is running in another (probably the main thread of your application). retrieving properties from object in another thread is allowed, but changing them is not.
 
The solution is to get into the UI thread first and then change the selected item. When using threads in a Windows form, this can be done by calling the Invoke statement. But there is an easier alternative if you are using the BackgroundWorker (although in more complex situations one might prefer to use the Invoke).
 
The ProgressChanged event is handled in the UI thread. This is were you want to update the listView1. The ReportProgress has two signatures:
    ReportProgress(int);
    ReportProgress(int, object);
 
The latter has a extra parameter which you can use to send any object (including custom classes). You can uses this to pass the value j to the UI thread. The ProgressChangedEventArgs.UserState will contain the value of j.
 
        private void StartButton_Click(object sender, EventArgs e)
        {
            //Some code

            //Worker1.RunAsync(count);  //Old way to start - in your old call you already pass a variable, I assume its called count.
            //Determine current selected
            int currentSelected = 0;
            for (i = 0; i < ListView1.Items.Count; i++)
            {
                if (ListView1.Items[i].Selected == true)
                {
                    currentSelected = i;
                    break;
                }
            }
            // I used a Tuple type, this is a way to pass two (or more) variable in one object
            Worker1.RunAsync(new Tuple<int, int>(count, currentSelected));
        }
 
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            int count = 0; //Changed this
            int sum = 0;
            int currentSelected = 0;
            if (e.Argument is Tuple<int, int>)
            {
                count = (e.Argument as Tuple<int, int>).Item1;
                currentSelected = (e.Argument as Tuple<int, int>).Item2;
            }
            bool isCurrentSet = false;
 

            for (int i = 0, j = 0; i < listView1.Items.Count && j < listView1.Items.Count; j++)
            {
                if (!isCurrentSet)
                {
                   j = currentSelected;
                   isCurrentSet = true; // Make sure j is only changed in the first call.
                }
 
                backgroundWorker1.ReportProgress(i * 100 / count, j);
                Thread.Sleep(2000);
                if (backgroundWorker1.CancellationPending)
                {
                    e.Cancel = true;
                    break;
                }
 

                sum += i;
                backgroundWorker1.ReportProgress(i * 100 / count);
                Thread.Sleep(2000);
            }
 
            e.Result = sum;
        }
 
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            //Report the progress, this might be some different code
            progressBar1.Value = e.ProgressPercentage;
 
            //Update the listView1, only if the index of the selected item is supplied
            if (e.UserState != null)
            {
                int j = (int)e.UserState;
 
                if (j != 0)
                {
                    listView1.Items[j - 1].Selected = false; 
                }
 
                listView1.Items[j].Selected = true;  
            }
        }
 
This will probably solve the error you encountered.
 
You might need to check the progress reporting too. The progress remained at 0 because the i value wasn't increased.
  Permalink  
v2
Comments
vasanthkumarmk at 19-Aug-12 0:20am
   
Ok thanks, i can it.
vasanthkumarmk at 19-Aug-12 0:39am
   
Thanks a lot, its working. But
 
Can you explain about these two signatures.
ReportProgress(int);
ReportProgress(int, object);
 
Where i can declare in my program.
Martijn Kok at 19-Aug-12 10:26am
   
If you look into the Visual Studio help for the BackgroundWorker.ReportProgress (or goto http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.reportprogress.aspx) you will see that there are two versions of the ReportProgress method.
 
You can use them based on the parameters you will supply. In your code you are using them both. If you only supply 1 parameter as an int (like in backgroundWorker1.ReportProgress(i * 100 / count)) then you are using the ReportProgress(int). If you read the help documentation you will see this one only can be used to report te progress.
 
When you supply 2 parameters (of which the first must be an int and the second can be any kind of object) you will use the ReportProgress(int,object). In the code this is the backgroundWorker1.ReportProgress(i * 100 / count, j). In this example the 2nd parameter is also an int, but it could be anything. In the helpdocumentation you will see that this parameter represents the UserState.
 
Having 2 or more signatures of the same method is called method overloading. You can use it in your own code too. For instance look at this page http://csharp.net-tutorials.com/classes/method-overloading/
vasanthkumarmk at 22-Aug-12 5:10am
   
Dear Sir,
I need to set Seconds for play items one by one from the list view. so I have set time using single text box. Code as below for set timing for selected list view items.
listView_playlist.SelectedItems[0].Tag = txtbox_timertime.Text;
txtbox_timertime.Text = "";
txtbox_timertime.Text =
listView_playlist.SelectedItems[0].Tag.ToString();
string a = listView_playlist.SelectedItems[0].Tag.ToString();
listView_playlist.SelectedItems[0].SubItems.Add(a);
MessageBox.Show("File Name of " + listView_playlist.Selected
 

i am getting timing from text box (named as txtbox_timertime.Text) and i make some alteration of what you code gave me. Just instead sleep i am using the textbox time. As below shows for your code include my alteration:
try
{
int count = (int)e.Argument;
int sum = 0;
 

for (int i = 0, j = 0; i < listView_playlist.Items.Count && j < listView_playlist.Items.Count; j++)
{
backgroundWorker1.ReportProgress(i * 100 / count, j);
int time = Convert.ToInt32(txtbox_timertime.Text);
Thread.Sleep(time * 1000);
 
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
break;
}
 
sum += i;
backgroundWorker1.ReportProgress(i * 100 / count);
Thread.Sleep(time * 1000);
}
 
e.Result = sum;
}
catch { }
 

What my problem is the Seconds not works proper timing. If we give 25 Seconds it will works for 2 seconds only.
 
So What changes i have do for recertify this solution
 
Awaiting your reply.
 
Regards
Vasanth
Martijn Kok at 22-Aug-12 5:32am
   
Hi Vasanth,
 
I'll look into it in about a few hours (currently working). You should also try to make this a new question. This will give other experts a chance to look at the problem too. All the experts together will definitly know more than I alone, and they will see the new question, but I doubt they will see this comment.
 
My first approach to this new problem would be to check which value is actually in the time int. Either place a breakpoint or insert a Console.WriteLine(time.ToString()); after the 'int time = ...' line. Check the output view of Visual Studio. Does it show 25 seconds or 2 seconds.
 
I would expect 2 seconds. So the problem is not the thread by the value in txtbox_timertime.Text.
 
vasanthkumarmk at 22-Aug-12 5:41am
   
ok i can check this.
Martijn Kok at 22-Aug-12 9:30am
   
I do have some additional questions to understand your question.
 
1) What are you showing in the listview? Titles of songs?
2) What kind of class is put in the items of the Listview? Only strings with the titles of songs or something else like a class or a structure
3) if is is a class or a structur (or something like a DataRow) which fields are there in that class
4) I assume you only has 1 txtbox_timertime on your form?
5) How are the values in this txtbox_timertime.Text changed. By code or do you need to input the time.
 
You really might want to post your question as a new question. I will try help you on this one, but actually you are asking a new question. Your first question was for the most part about the BackgroundWorker, and this new question is more about a ListView. Until 5 days ago I have never looked at a ListView. If have used ListBox and I think that I know what the problem is, but I'm not as sure as with the BackgroundWorker question. Other developers might have a lot more experience with the ListView.
 
I'll study the ListView a little more. Maybe I'll find something to help you.
vasanthkumarmk at 22-Aug-12 13:46pm
   
Thanks for you asking this.... Lets i explain my aim of the task:
I have below items in my project,
1. Listview
2. Buttons - 4 [Add,Play,Pause,Settime]
3. Textbox -1 [Enter the Time for play (in seconds)]
 
While i click the Add button, The open dialog will opened i have to choose files and added in the List view item (For Example 10 Files), First i have to Click top most First item (Index 0) From the List View. Then enter the Time in the textbox then Click settime Button.
It will shows the Listview second column near the appropriate File name. Like that i have done all 10 items.
 
Then i click the Play button, The item selection (with blue backcolor) select the First
item then based on the our Entered Timing (Seconds) selection will moves one by one upto
the last time, then i will loop again start from first item.
 
When i Click the Pause Button Selected item will pause.
 
What I have done sofar this task:
Textbox:
Time for play ---> Enter the timing for every playlist item was finished.
 
Add --> Adding the files part everything is was finished.
Play--> While i click the play using background worker it will plays one by one
But My problem is:
1. Timing not set properly
2. I need to select Particular file from listview (Ex:Index=8) then click the
Play button, File will play from selected file (It is not possible). Itwill select first file and our selected file (Index=8) both are playing at same time.
Pause -> When i click the pause entire playlist will stop, But pause the play is not works
 
I hope now you cleared my idea. If you want to post this one as New Question i am ready to post. But i sure others not understand this c Except you. You only understand this because i am using your code
and the same time you know my task details from beginning to so far.
 
Regards,
Vasanth
Martijn Kok at 22-Aug-12 15:12pm
   
I have 2 more questions after reading this explanation.
 
Concerning problem 1: how do you store time in the ListView. And how do you store the filename. Can you show me the part where you store the value of the txtbox_timertime.Text into the listview item (1 line should do). And also the code where you store the filename into the listview
 
Concerning problem 2) Can you verify what the value of the following property of the ListView is: MultiSelect. I would guess it is true?
vasanthkumarmk at 23-Aug-12 2:18am
   
Sure!!! I have Clear what doubt in your mind.
 
1. Store time in the Listview:
I have entered time in the txtbox_timertime (Textbox) using below code. Just i click the first item from list view, enter the time in the textbox , then click the second item from listview, enter the time in th text box,
Code :
 
if (listView_playlist.SelectedItems.Count > 0)
{
listView_playlist.SelectedItems[0].Tag = txtbox_timertime.Text;
txtbox_timertime.Text = "";
txtbox_timertime.Text = listView_playlist.SelectedItems[0].Tag.ToString();
string a = listView_playlist.SelectedItems[0].Tag.ToString();
listView_playlist.SelectedItems[0].SubItems.Add(a);
MessageBox.Show("File Name of " + listView_playlist.SelectedItems[0].Text + " set " + a.ToString() + " Seconds");
 
// MessageBox.Show(listView_playlist.SelectedItems[0].Tag.ToString());
// textBox2.Text = listView_playlist.SelectedItems[0].Tag.ToString();
}
else
{
MessageBox.Show("Please Select Item and set the value", "InSTa Title");
}

2.File name getting:
Just I get my file name and path to store two temporary text boxes (txtpath.Text, txtfilename.Text),
Code as belows:
if (openFileConfig.ShowDialog(this) == DialogResult.OK)
{
try
{
//Adding files to playlist
var fileNamenoextension = System.IO.Path.GetFileNameWithoutExtension(openFileConfig.FileName);
txtpath.Text = openFileConfig.FileName;
txtfilename.Text = fileNamenoextension;
 
if (listView_playlist.Items.Count >= 0)
{
//listview.Items.Add(System.IO.Path.GetFileNameWithoutExtension(openfile.FileName),openfile.FileName);
listView_playlist.Items.Add(txtfilename.Text).SubItems.Add(txtpath.Text);

}
}
catch (Exception) { }
 

I hope now you little bit clear, otherwise i am ready to come teamviewer.
One small suggestion please give some personal id for our both communication, This out public post queries is not good. If your wish.
Regards
Vasanth
Martijn Kok at 23-Aug-12 4:26am
   
Hi Vasanth,
 
This is my last post on this item. I asked you twice to make a new question so that all the other experts could help also. As you state yourself that public post queries are no good. I wish to stick to the rules of codeproject. What I can do is watching out for questions you ask in the Quick Answers section. I'll help if I have the knowledge and time.
 
Concerning the problem at hand. I can give you a simple hint. Each item in the playlist has it's own time. Stored in de listView_palylist.SelectedItems[index].Tag. So when you need the time in the background worker get if from that tag instead off the txtbox_timertime.
 
int time = Convert.ToInt32(listview_playlist.Selecteditems[0].Tag.ToStrng());
 
And you should make listview_palylist.MultiSelect = false; This prevents the possibility that multiple items are selected.
 
I hope this is of use. If you have more questions ask a new question in the 'Quick Answers' section. So everyone can give it a try to solve.
vasanthkumarmk at 23-Aug-12 5:14am
   
Ok, thank you very much for help me to finishing my task. Thanks a lot.
vasanthkumarmk at 10-Sep-12 8:00am
   
Dear sir,
This is my Final Question. I need to keep the pause and play button in this task. Pause -> Listview items stops the Which current items selected. Play -> Listview items starts play from which items stops (not from first items). I tried that it will pause the selected item. But when i click the play it will from top most first item. It won't play from the next of the pause item. Please give this final solution.
Martijn Kok at 10-Sep-12 9:10am
   
Hi Vasanth,
 
I have made some changes in the solution code. When calling RunAsync you'll need to pass an extra parameter. Because you are already using the argument to pass count, I've used a Tuple to pass on a second argument (the currently selected item).
 
In the loop the variable j is set to this currentSelected. A boolean flag is set to true to ensure that this only happens the first time the code is called.
 
I wasn't able to test the code. I don't hope I made typing errors. Let me know if you run into a problem.
Martijn Kok at 10-Sep-12 9:28am
   
I just realised that I don't know which version of C# you are using. Tuples exist in C# 4.0 (and probably in 3.5). Let me know if you are using an older version of C# and can't use Tuples.
vasanthkumarmk at 11-Sep-12 0:51am
   
Dear sir,
Thank you very much for your reply. I am trying that code and I get you sir.
 
Thanks again
vasanthkumarmk at 11-Sep-12 1:36am
   
Thank so much sir, your code is working good. Sorry for your disturbance. Once again I thank to you spending your valuable time for me. If any more doubts I will ask you sir. Don't Mistake me. Because you know very well clear about my task.
Regards
Vasanth
vasanthkumarmk at 11-Sep-12 1:38am
   
Thank you so much sir, Your code is working good. Thank for you spending your valuable time for me. Sorry for disturbance, If any more doubts I will ask you, Please resolve my doubts. Because you only understand my task very clearly.
Thanks a lot........
Regards,
Vasanth
Martijn Kok at 11-Sep-12 3:09am
   
You're welcome.
 
Regards,
 
Martijn
vasanthkumarmk at 11-Sep-12 5:13am
   
Sir,
I have small issue. Play & Pause is working well. But some minor issues is there. While play the list, the file name appears with blue back colour identification. When I Click the Pause button it will stops the current item (without background blue colour identification) shows some Gray back colour. Then again start to click the Play button Next item only shows the blue back colour. Currently Pause items not starts with blue back colour. It shows only Gray Colour Identification.
 
This is my Pause button Coding :
 
private void btn_PLpause1_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
}
 
I hope this is a small issue. Where I can change the code here.
Martijn Kok at 11-Sep-12 5:23am
   
Are you using WPF? (Or WinForms)
vasanthkumarmk at 11-Sep-12 6:21am
   
No sir, I am Using WinForms only.
Martijn Kok at 11-Sep-12 7:15am
   
The fist thing I thought about is that when you click the ListView it has focus. When you click the pause button the focus shifts to the Pause button. It is quite common that an unfocussed control has different colors that a focussed one.
 
You can test it by clicking an item in the ListView. Then press the Tab button. Probably the color changes. Can you test this?
 
Problem is that I don't know how to change the colors in WinForms. I do know how to in WPF.
 
vasanthkumarmk at 11-Sep-12 7:36am
   
ok sir thankyou
vasanthkumarmk at 14-Sep-12 13:50pm
   
Please give reply for my questions in question page. My Question topic is :listview items save one folder
Martijn Kok at 15-Sep-12 8:09am
   
I read the question, but I do agree with the others that there is not really a question. It is not clear what the problem is and what needs to be solved.
 
In general it is best to describe the problem and descibe what you have done yourself to solve it. Code examples and error message will make it a lot clearer.
 
If you are new to a problem you could try google. If you search "C# get filenames in folder" you will find code how to read files from a folder. Search an example which looks 'good' and try it. If you run into problems or it is not would you really want, you can search further or ask in codeproject. Give examples of your code, that will help. Like this question about the backgroundworker. That was a great help in solving the problem.
vasanthkumarmk at 6-Nov-12 11:38am
   
Hi Martijn,
I hope you remember me.
After long days back i came in front of you.
 
I hope you remember my project.
 
I have 2 Issues i need your help to resolve those issues. Below i mentioned the issues.
Issue 1: (Pause & Play)
What coding you send that only i use in my project (Playlist). Thats working very well. But i need to implement the pause and play, When i start to play from the listview after click the pause button it will pause the current file from the listview and the same time while click the play it will start the next file then play.
 
Issue 2 : (Time for next file)
Here i mentioned your coding for play time next file one by one using Thread.Sleep() method.
But i need to give my values of particular second from the text box value Thread.Sleep(txtbox.sleep); But here time not takes properly
 
for (int i = 0, j = 0; i < listView1.Items.Count && j < listView1.Items.Count; j++)
{
if (!isCurrentSet)
{
j = currentSelected;
isCurrentSet = true; // Make sure j is only changed in the first call.
}

backgroundWorker1.ReportProgress(i * 100 / count, j);
Thread.Sleep(2000); //Here
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
break;
}

 
sum += i;
backgroundWorker1.ReportProgress(i * 100 / count);
Thread.Sleep(2000);
}
I try it long times but not works properly Please give me the solution. I very eager to expecting your solution. You are only my hope.
 
Thanks & Regards
Vasanth
Martijn Kok at 9-Nov-12 9:45am
   
Hi Vasanth,
 
I wasn't able to answer earlier. I have been working a lot the past few days.
 
I'll look at your questions this weekend. It has been a while and I have to study the code. I'll hope I will be able to answer your questions.
Martijn Kok at 12-Nov-12 2:40am
   
Hi Vasanth,
 
I had some hard time getting into the question again. I think I understand your questions.
 
Issue 1: after pause you want the paused item to continue? And if so, do you want to restart the timer or continue. For instance if you want to play for 25 seconds and you have played 6 seconds already. Should it restart at 25 seconds or continue with the remaining 19 seconds?
 
Issue 2: if you enter another time (lets say 25 seconds, your playlist should run for 25 seocnds.
Martijn Kok at 12-Nov-12 10:16am
   
Hi Vasanth,
 
I hope i have a solution. Not sure if it also solves issue 1. I have put the code at the end of this thread.
vasanthkumarmk at 12-Nov-12 21:08pm
   
ok Martijin
vasanthkumarmk at 17-Sep-12 5:23am
   
I am using Windows Application with C# Code.

I have ListView item contains some of the files. The listview files will store the Excel Sheet using below code.
Collapse | Copy Code
private void btn_PLLoad_Click_2(object sender, EventArgs e)
{

StringBuilder sb = new StringBuilder();

Microsoft.Office.Interop.Excel.Application xla = new Microsoft.Office.Interop.Excel.Application();
xla.Visible = true;

Microsoft.Office.Interop.Excel.Workbook wb = xla.Workbooks.Add(Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);

Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)xla.ActiveSheet;

int i = 1;

int j = 1;

foreach (ListViewItem comp in listView_playlist.Items)
{

ws.Cells[i, j] = comp.Text.ToString();

//MessageBox.Show(comp.Text.ToString());
 
foreach (ListViewItem.ListViewSubItem drv in comp.SubItems)
{

ws.Cells[i, j] = drv.Text.ToString();

j++;

}

j = 1;

i++;

}



}
It will directly stores the listview datas to Excel sheet.

Then I Close my Application. When the click the button using open file dialogue to open that Excel Sheet (Which listview item data saved Excel Sheet). I need to retrieve again saved Excel Sheet datas to my listview.

I Posted the Question in public.
 
Regards
Vasanthakumar
Member 10066868 at 18-Apr-14 1:10am
   
4
vasanthkumarmk at 19-Aug-12 15:30pm
   
ok thank you very much..... Your posting very useful for me. So many thanks to you
vasanthkumarmk at 22-Aug-12 5:09am
   
Dear Sir,
I need to set Seconds for play items one by one from the list view. so I have set time using single text box. Code as below for set timing for selected list view items.
listView_playlist.SelectedItems[0].Tag = txtbox_timertime.Text;
txtbox_timertime.Text = "";
txtbox_timertime.Text =
listView_playlist.SelectedItems[0].Tag.ToString();
string a = listView_playlist.SelectedItems[0].Tag.ToString();
listView_playlist.SelectedItems[0].SubItems.Add(a);
MessageBox.Show("File Name of " + listView_playlist.Selected
 

i am getting timing from text box (named as txtbox_timertime.Text) and i make some alteration of what you code gave me. Just instead sleep i am using the textbox time. As below shows for your code include my alteration:
try
{
int count = (int)e.Argument;
int sum = 0;
 

for (int i = 0, j = 0; i < listView_playlist.Items.Count && j < listView_playlist.Items.Count; j++)
{
backgroundWorker1.ReportProgress(i * 100 / count, j);
int time = Convert.ToInt32(txtbox_timertime.Text);
Thread.Sleep(time * 1000);
 
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
break;
}
 
sum += i;
backgroundWorker1.ReportProgress(i * 100 / count);
Thread.Sleep(time * 1000);
}
 
e.Result = sum;
}
catch { }
 

What my problem is the Seconds not works proper timing. If we give 25 Seconds it will works for 2 seconds only.
 
So What changes i have do for recertify this solution
 
Awaiting your reply.
 
Regards
Vasanth
Martijn Kok at 12-Nov-12 11:39am
   
Hi Vasanth,
 
I think I have a solution. I can't test it though and thus I'm not sure if it will solve issue 1.
 
First of all add the following code:
 
private int timeInMilliSecondsRemaining = 0; //Initialize the time at 0.
 
private bool DoWaiting()
{
while (timeInMilliSecondsRemaining > 0)
{
Thread.Sleep(200); // 200 milliseconds
timeInMilliSecondsRemaining -= 200; // substract waited time from timeremaining
if (backgroundWorker1.CancellationPending)
{
return true;
}
}
 
timeInMilliSecondsRemaining = 0;
return false;
}
 
private void ResetTime()
{
// Only reset time if the current time has been finished, otherwise resume
if (timeInMilliSecondsRemaining <= 0)
timeInMilliSecondsRemaining = Convert.ToInt32(listview_playlist.SelectedItems[0].Tag.ToString());
//timeInMilliSecondsRemaining = Convert.ToInt32(txtboxSleep.Text);
}
 
Secondly change part of the loop into:
 
backgroundWorker1.ReportProgress(i * 100 / count, j);
//Thread.Sleep(2000);
//if (backgroundWorker1.CancellationPending)
//{
// e.Cancel = true;
// break;
//}
ResetTime();
e.Cancel = DoWaiting();
 
The code does the following. To pause you need something to pause. In the former code the backgroundworker did wait the required seconds and then checked to see if a cancellation was pending. So it was inpossible to stop halfway. The DoWaiting method checks every 0.2 seconds if a cancellation is pending.
 
To check the time remaining I added a int with the time remaining in milliseconds. When the time remaining reaches 0, the waiting will be finish. DoWaiting returns true if the pause button has been hit (assuming that your pausebutton will cancel the background worker).
 
To set the time remaining I added the ResetTime method. It will take the time form the playlist (you might need to mulitply the seconds with 1000, i forget that).
 
Concerning Issue 1 this also might be solved. When you push the start button the reset time function will check if there was a time remaining and the code will continue where it left. If you don't want this funcionality, then remove the 'if (timeInMilliSeccondsRemaing <= 0)'
 
I hope it will work
 
Regards
 
Martijn
vasanthkumarmk at 12-Nov-12 21:11pm
   
Hi Martijin,
 
Its a great Work......
I try it and will get back you.....
Thanks a lot again.....
 
Regards
Vasanth
vasanthkumarmk at 12-Nov-12 21:53pm
   
Hi Martijin,
 
You have done a great work.
 
I applied above code and get back you, before applied this code i need to clear one more thing.
 
When i start my playlist, after some times if i stop the playlist it takes some times to stop and getting message box like "Playlist Stopped", How can i stop very quickly without any time longer. I added the coding below for your reference:
 
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
try
{
 
//progressBar1.Value = 0;
if (e.Cancelled)
{
 
//this.listView_playlist.Items[this.listView_playlist.SelectedIndices[0]].Selected = false;
MessageBox.Show("Playlist Stopped","InSTa Title");
}
else
{
btn_PLpause_Click(sender, e);
btn_PLplay_Click(sender, e);
listView_playlist.Items[0].Selected = false;
 
}
}
catch { }
}
 
Thanks a lot Martijin......... Again and again
 
Regards
Vasanth
Martijn Kok at 13-Nov-12 0:40am
   
Hi Vasanth,
 
My mistake. Ater calling DoWaiting, I didn't break the execution of the code (which would result in calling the Thread.Sleep(2000) and thus waiting for 2 more seconds). Change the code to
 
ResetTime();
if (DoWaiting())
{
e.Cancel = true;
break;
}
 
Regards
 
Martijn
vasanthkumarmk at 14-Nov-12 11:15am
   
Hi Martijn,
 
Please send overall coding......
 
Thanks & Regards
Vasanthakumar
vasanthakumarmk@gmail.com
Martijn Kok at 15-Nov-12 4:38am
   
Hi Vasanth,
 
I'll send it in a view. The playlist part of the code is missing. I've never seen the actual code behind the ListView (I never really used a ListView in programs I wrote).
 
Due to the missing of part of the code, I have made guesses about parts, but I think you could fit it into your code.
 
Regards
Martijn
vasanthkumarmk at 27-Nov-12 5:57am
   
Hi Martijn,
CIDev at 10-Sep-12 9:49am
   
Very fine answer, Martijn, +5
Rahul VB at 21-Jan-14 1:39am
   
Hello Sir,
Very nice answer +5!
but i have a doubt:
 
As you said:
"retrieving properties from object in another thread is allowed, but changing them is not."
 
Why is that so? Why is it not allowed? Why does it throw an exception? Please dont mind my questions, its just inquisitiveness. It was an accepted wisdom for me, but whats the logical or technical reason behind it.
 
- Thanks,
Rahul
Martijn Kok at 21-Jan-14 2:24am
   
Hello Rahul,
 
It's actual a good question. I'm not sure if my technical knowledge is good enough to explain it clearly, but I hope my explanation will give some indication for you to search for more information on this topic.
 
A thread is more or less a seperate piece of executing code. Every program has at least one thread in which the program executes. Each thread has exactly one current line of execution (the yellow line when you are debugging your code in Visual studio). A thread does more than that. I also does something with memory management (I don't know the details). A thread owns the objects which are created in that thread.
 
Your code can run more than 1 thread. When your start a BackgroundWorker a new thread is created. Not Always the threads know of each other existance. Their life time might be different. In this case of the BackgroundWorker the background worker only exists as long as the background worker executes. As soon as the backgroundworker is completed is stops existing.
 
This might create a problem in memory management. When the backgroundworker dies, the objects it owns die too. If it was allowed that one thread sets object in another thread this would cause a problem.
 
There are several solutions to this problem, which all involve calling the other thread first an than setting the object. This can be done using an Invoke (in WinForms). WPF uses something called the Dispatcher object. In the background worker you can use the ProgressChanged event.
Rahul VB at 21-Jan-14 3:30am
   
Hello Sir,
Your explanation was good. But i think to get to the root of the answer we need to reverse engineer the question. The solution was to use "invoke". So we must see what invoke does. From that we can get a hint as to what should be the reason behind it. Your knowledge is good, but the only thing which is required is : you need to ask your self "What is the reason behind anything? why is this happening?".
 
Thanks,
-Rahul
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 CPallini 325
1 Sergey Alexandrovich Kryukov 249
2 OriginalGriff 230
3 George Jonsson 130
4 ChauhanAjay 104
0 OriginalGriff 6,464
1 Sergey Alexandrovich Kryukov 5,915
2 CPallini 5,175
3 George Jonsson 3,559
4 Gihan Liyanage 2,522


Advertise | Privacy | Mobile
Web04 | 2.8.140916.1 | Last Updated 10 Sep 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100