• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 240
  • Last Modified:

BackGroundWorker Controls help

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
hassanayoub85
Asked:
hassanayoub85
  • 5
  • 3
  • 3
  • +1
1 Solution
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Can you give more details?...you may not need the BackgroundWorker() controls.  What needs to be done in the Timers/BackgroundWorkers()?
0
 
hassanayoub85Author Commented:
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
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
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
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
BuggyCoderCommented:
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
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Out of curiosity, why do you recommend ManualResetEvent over Sleep?  They both will block the current thread...
0
 
BuggyCoderCommented:
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
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
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
 
hassanayoub85Author Commented:
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
 
käµfm³d 👽Commented:
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
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
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
 
hassanayoub85Author Commented:
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
 
BuggyCoderCommented:
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
 
käµfm³d 👽Commented:
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

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

  • 5
  • 3
  • 3
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now