Solved

BackGroundWorker Controls help

Posted on 2012-04-13
13
230 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
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

 
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
 
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 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 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 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

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Page navigation in windows phone 8.1 application not working. 5 24
Device Location 4 29
Coding C# in Linux 8 60
insert value of checklistbox checked 4 24
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…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

813 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

12 Experts available now in Live!

Get 1:1 Help Now