Solved

BackGroundWorker Controls help

Posted on 2012-04-13
13
231 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 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
Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

 
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

733 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