[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

BackGroundWorker Controls help

Posted on 2012-04-13
13
Medium Priority
?
238 Views
Last Modified: 2012-04-15
Dear,
Any one can help me in writing the code which allow me running 2 timers in a 2 different background worker controls?
Thx
0
Comment
Question by:hassanayoub85
  • 5
  • 3
  • 3
  • +1
13 Comments
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 37844723
Can you give more details?...you may not need the BackgroundWorker() controls.  What needs to be done in the Timers/BackgroundWorkers()?
0
 

Author Comment

by:hassanayoub85
ID: 37845258
Let's say I have 2 timers
timer1 create file each second.
timer3 rename file each second.
How to run both of them in backgroundworker?
Thx
0
 
LVL 86

Accepted Solution

by:
Mike Tomlinson earned 2000 total points
ID: 37845370
Since the BackgroundWorkers run in their own Threads, you can simply use a While loop with a Sleep() call (instead of a Timer):
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                System.Threading.Thread.Sleep(1000);
                // create some file
            }
        }

        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                System.Threading.Thread.Sleep(1000);
                // rename some file
            }
        }

Open in new window

0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 20

Expert Comment

by:BuggyCoder
ID: 37845611
rather than using timer or sleep, i suggest you use ManualResetEvent inside your do work event handler of each backgroundworker.

you can do your work and let your eventhandle wait for specified amount of time before again hitting the code to do your work again...

here is how to use manual reset event in c#:-
http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.aspx
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 37845623
Out of curiosity, why do you recommend ManualResetEvent over Sleep?  They both will block the current thread...
0
 
LVL 20

Expert Comment

by:BuggyCoder
ID: 37845630
The events are kernel primitives provided by the OS/Kernel that's designed just for these sort of things.

In short, when a thread waits on an event, it's put on a waiting list for that event and marked as non-runnable. When the event is signaled, the kernel wakes up the ones in the waiting list and marks them as runnable and they can continue to run.

It's naturally a huge benefit that a thread can wake up immediately when the event is signaled, vs sleeping for a long time and recheck the condition every now and then.
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 37845663
Right...I understand what ManualResetEvent() is for, and you have good points about it being able to wake up before the timeout via signalling.

In this case, though, the author hasn't indicated any type of signalling requirements.  From the description thus far it seems that he just needs one second delays before restarting a segment of code that is running in a different thread.

It just seems overkill since there will be extra overhead using ManualResetEvent().  In fact, the BackgroundWorkers() may be overkill as well.  He may be able to simply use System.Timers.Timer (which run in their own thread) and specify the Interval.

The vague overall problem description makes it hard to recommend a good approach.
0
 

Author Comment

by:hassanayoub85
ID: 37847093
mmm, I am little bit, actually not a little bit, but not understanding anything!!! LOL.
What I want is as simple as:
1- Taking screenshot from he computer each 10 seconds.
2- Save them to the Hard Disk.
3- another function have ti be run each 5 seconds to check if there is file created, it will upload them to the server, else, do nothing.
That's exactly what I want to do.
So does backgroundworker control can solve this or need the other mentioned method?
Thx
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37847293
It sounds like there is a looming race condition in there. How are you ensuring that a file has been *completely* written to the disk before the 2nd function comes into to upload to the server? Why is there a 2nd function to perform this task? Can it not be uploaded just after the write out to disk? What about doing an asynchronous upload to the server just after the write to disk completes?
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 37847334
Good points kaufmed.  Another approach would be to use a different file name for each screenshot.  Either date/time stamp it, or maybe use a temp file name provided by the OS.
0
 

Author Comment

by:hassanayoub85
ID: 37849065
kaufmed:

1- No need to be sure for that, the funciton will check f there is a new file in the directory, of so, it will upload it then delete it, if not it will do nothing.
2- A second funciton is needed due to that there is many files to being uploaded. from many directories, even files created from different proccess.
3- No, there is different functions, 1 to create files, 1 to to upload.

Idle_mind:
Already doing that, images are saved based on time.

So now, can I get a solution?
0
 
LVL 20

Expert Comment

by:BuggyCoder
ID: 37849133
well just see if this one helps, i took a timer, on tick of timer(10 secs) i started by BGWorker. In BG Worker i capture the screen and post the response to a uri as byte stream. Didn't save the data in file:-

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            tmrMain.Start();
        }

        private void TmrMainTick(object sender, EventArgs e)
        {
            bgWorker.RunWorkerAsync();
        }

        private void BgWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            var c = new WebClient();
            c.UploadData(new Uri("http://www.com"), ScreenCaptureHandler.CaptureScreen());
            e.Result = true;
        }

        private void BgWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //File Uploaded
        }
    }

    public class ScreenCaptureHandler
    {
        public static byte[] CaptureScreen()
        {
            var s = Screen.PrimaryScreen.Bounds.Size;
            var bmp = new Bitmap(s.Width, s.Height);
            var g = Graphics.FromImage(bmp);
            g.CopyFromScreen(0, 0, 0, 0, s);

            var memStream = new MemoryStream();
            bmp.Save(memStream, ImageFormat.Jpeg);

            var arrRet = memStream.ToArray();
            memStream.Close();

            return arrRet;
        }

Open in new window

0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 37849459
No need to be sure for that, the funciton will check f there is a new file in the directory, of so, it will upload it then delete it, if not it will do nothing.
A "new" file does not necessarily mean a complete file. You first function could still be in the process of writing out the file by the time the second function comes in checking for files. This is the race condition.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
Despite its rising prevalence in the business world, "the cloud" is still misunderstood. Some companies still believe common misconceptions about lack of security in cloud solutions and many misuses of cloud storage options still occur every day. …

825 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question