Reputation: 21
I'm new to Threading but I've read threads here on BackgroundWorker (BW) and mostly understand the material. I suspect BW is not the correct solution but let me ask. I have an object (GPS Emulator) that does its work in a loop mostly waiting (Thread.Sleep()) but occasionally raising an event that the UI listens for. I want the UI to be responsive of course so it would be nice to put the work of the object in the background (as in gps.Start()). On the UI I want to have the ability to Pause, Resume, and Stop the GPS. I figured I could do this by setting appropriate flags in the GPS object that would break the loop running in the background. What I don't understand is what happens to the events that are raised by the GPS. The Thread that the event is raised on is not the Thread that is listening and so it seems, the UI can't respond correctly (as in painting the new GPS point on the UI). Am I missing something wrt BW or is there a better (but still simple) way of doing this?
Upvotes: 2
Views: 401
Reputation: 18430
I think you can use the ProgressChanged event of the BackgroundWorker to monitor the the event on your own thread.
This is just an example modify it according to your requirement
Create a class to hold cordinates postion:
public class Position
{
public int Lat{get;set;}
public int Long {get;set;}
}
In your DoWork
method do somthing like this:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//Perform what ever is your task and when you get somthing like a GeoPosition cordinate
Position pos = new Position();
pos.Lat = 100;
pos.Long = 200; // just some position data
//pass it on to progress changed event
//any integer between 0 to 100 that tells how much you have done or just pass 0
backgroundWorker1.ReportProgress( 0, pos);
}
in your progress changed event handler :
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//retrieve position from userstate
Position pos = e.UserState as Position;
some_counter_or_progressbar.Value = e.ProgressPercentage;
textboxLatitude.Text = pos.Lat.ToString();
textboxLongitude.Text = pos.Long.ToString();
}
I'm sure you got the Idea...
Upvotes: 3
Reputation: 346
So if I understood this right, the events fired by the GPS emulator result in an UI update and you want to be able to control the running of the GPS emulator from your UI. If this is indeed correct, I'd use the event WaitHandle constructs, either Auto or Manual based on the situation
Upvotes: 0