Solved

BackGroundWorker Controls help

Posted on 2012-04-13
13
228 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 85

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 85

Accepted Solution

by:
Mike Tomlinson earned 500 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
 
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 85

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
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 85

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 74

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 85

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 74

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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

707 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now