How to download files in a blocking/synchronous manner? - c#

I am pretty new to silverlight and was very surprised to see that only asynchronous file downloading can be done. Well, I've attempted to counter act this by just setting a flag and waiting on it to change..
This is my simple code
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
WebClient webClient = new WebClient();
webClient.DownloadProgressChanged +=
new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
webClient.OpenReadAsync(new Uri("/trunk/internal/SilverLightInterface.ashx?xxid=XXX", UriKind.Relative));
while (XmlStateStream == null) { }
lblProgress.Content = "Done Loading";
}
void webClient_DownloadProgressChanged(object sender,
DownloadProgressChangedEventArgs e) {
lblProgress.Content = "Downloading " + e.ProgressPercentage + "%";
}
volatile Stream XmlStateStream = null;
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error != null)
{
lblProgress.Content = "Error: " + e.Error.Message;
return;
}
XmlStateStream = e.Result;
}
This is causing Firefox to actually freeze up(which is extremely annoying when I'm doing other things while developing) (btw, kudos to firefox cause I tested it and firefox froze, but I didn't lose what I was typing here after restoring)
I don't understand why the while(XmlStateStream==null){} is causing a freeze up. Is there some attribute for locks or volatile(other than what I already have) or am I in the wrong part of the Silverlight page lifecycle or something?
I'm really confused as to why this is not working.
Also, this is silverlight 3.0

Most likely, this code is running in the UI thread that handles all of the web browser's interaction with the user. This is why you won't find any blocking operations - because anything that blocks will freeze the UI in exactly the same way that you saw! What's more, if the UI thread also handles network IO (which is common), then you'll deadlock here because the asynchronous operation you're waiting on will never finish.
I'm afraid you'll just have to rewrite your code as a state machine driven by asynchronous operations.

Whilst you need to get with the asynchronous nature of things in Silverlight you can use C# 3 syntax to keep things a bit more together:-
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
DownloadXmlStateStream();
}
void DownloadXmlStateStream()
{
WebClient webClient = new WebClient();
webClient.DownloadProgressChanged += (s, e) => {
lblProgress.Content = "Downloading " + e.ProgressPercentage + "%";
}
webClient.OpenReadCompleted += (s, e) => {
if (e.Error != null)
{
lblProgress.Content = "Error: " + e.Error.Message;
}
else
{
XmlStateStream = e.Result;
lblProgress.Content = "Done Loading";
}
}
webClient.OpenReadAsync(new Uri("/trunk/internal/SilverLightInterface.ashx?xxid=XXX", UriKind.Relative));
}

You need to use the DownloadFileCompleted event.
delete this:
while (XmlStateStream == null) { }
lblProgress.Content = "Done Loading";
add this:
webClient.DownloadFileCompleted +=
new DownloadFileCompletedEventHandler(webClient_DownloadFileCompleted);
and this:
void webClient_DownloadFileCompleted(object sender, AsyncCompletedEventHandler) {
lblProgress.Content = "Done Loading";
}
If you really must have synchronous downloading, you need to "poll" for the download being complete less often. Try calling System.Threading.Thread.Sleep() with a delay of 50-250ms from within your busy-wait loop.
Although this will reduce the wasteful CPU utilization of your code, it's possible that it will not fix the UI responsiveness problem. It depends on whether the thread that's calling your MainPage_Loaded is the only one that can call UI update events. If that's the case, then the UI simply can not update until that handler returns.

By blocking until the file is downloaded, you're not only blocking the UI thread of your silverlight app - you're also blocking the UI thread of the browser, it would seem.
All you really want to do (I presume) is stop your app doing anything until the download completes. Try adding this line to MainPage_Loaded:
LayoutRoot.IsHitTestVisible = false;
Remove your blocking while loop and the completed message (the last two lines).
In webClient_OpenReadCompleted, add:
LayoutRoot.IsHitTestVisible = true;
lblProgress.Content = "Done Loading.";
And everything should work the way I think you want.
Here's the full code:
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
WebClient webClient = new WebClient();
webClient.DownloadProgressChanged +=
new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
webClient.OpenReadAsync(new Uri("/trunk/internal/SilverLightInterface.ashx?xxid=XXX", UriKind.Relative));
LayoutRoot.IsHitTestVisible = false;
}
void webClient_DownloadProgressChanged(object sender,
DownloadProgressChangedEventArgs e) {
lblProgress.Content = "Downloading " + e.ProgressPercentage + "%";
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error != null)
{
lblProgress.Content = "Error: " + e.Error.Message;
return;
}
LayoutRoot.IsHitTestVisible = true;
lblProgress.Content = "Done Loading.";
}

Related

C# Background Worker Append TextBox

first off I'd like to say I'm brand new to C# so I am not too aware with how the background worker is supposed to be implemented. I have a GUI program that basically pings a domain a returns the response to a textbox. I am able to get it to work normally, however, it freezes the code because it is running on the same thread which is why I am trying to implement a background worker.
Here is the basic setup
private void button1_Click(object sender, EventArgs e)
{
url = textBox1.Text;
button1.Enabled = false;
button2.Enabled = true;
bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
bgWorker.RunWorkerAsync();
}
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
do
{
if (bgWorker.CancellationPending)
break;
Invoke((MethodInvoker)delegate { monitor(); });
} while (true);
}
public void monitor()
{
textBox2.AppendText("Status of: " + url + "\n");
Status(url);
System.Threading.Thread.Sleep(30000);
}
private void Status(string url)
{
// This method does all the ping work and also appends the status to the Text box as it goes through , as OK or down
}
I have not worked with bgworkers before and as you can imagine it's confusing. I've looked at tons of other articles and I can't seem to get it. Sorry if the code looks crazy, I'm trying to learn.
Use Microsoft's Reactive Framework (NuGet "System.Reactive.Windows.Forms" and add using System.Reactive.Linq;) and then you can do this:
private void button1_Click(object sender, EventArgs e)
{
var url = textBox1.Text;
Observable
.Interval(TimeSpan.FromMinutes(0.5))
.SelectMany(_ => Observable.Start(() => Status(url)))
.ObserveOn(this)
.Subscribe(status => textBox2.AppendText("Status of: " + status + "\n"));
}
You then just need to change Status to have this signature: string Status(string url).
That's it. No background worker. No invoking. And Status is nicely run on a background thread.
You've got several mistakes. First,
Invoke((MethodInvoker)delegate
{
monitor();
});
will call monitor() on your UI thread. In almost all cases you should not call methods on other threads. You especially should not call methods that block or do anything that takes more than a few milliseconds on your UI thread, and that is what this does:
System.Threading.Thread.Sleep(30000);
Instead of calling a method on another thread; submit immutable data to the other thread and let the thread decide when to handle it. There is an event already built in to BackgroundWorker which does that. Before you call bgWorker.RunWorkerAsync() do this:
url = new Uri(something);
bgWorker.WorkerReportsProgress = true;
bgWorker.WorkerSupportsCancellation = true;
bgWorker.ProgressChanged += Bgw_ProgressChanged;
private void Bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
textBox2.AppendText("Status of: " + url + ": " + e.UserState.ToString()
+ Environment.NewLine);
}
Your bgWorker_DoWork should look more like this:
void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
while (!bgw.CancellationPending)
{
System.Threading.Thread.Sleep(new TimeSpan(0, 0, 30));
var status = ResultOfPing(e.Argument as Uri);
bgw.ReportProgress(0, status);
}
e.Cancel = true;
}
and you should call it like this:
bgWorker.RunWorkerAsync(url);
You've got a second problem. BackgroundWorker creates a thread, and your thread is going to spend most of its time blocked on a timer or waiting for network responses. That is a poor use of a thread. You would be better off using completion callbacks or async/await.
The background worker is running on a thread pool thread, but your call to Status and Sleep is running on the UI thread. You need to move that stuff back into bgWorker_DoWork.
Try this code:
public partial class Form1 : Form
{
bool cancel;
public Form1()
{
InitializeComponent();
}
public void StartPinging()
{
this.cancel = false;
startButton.Enabled = false;
stopButton.Enabled = true;
responseBox.Clear();
responseBox.AppendText("Starting to ping server.");
responseBox.AppendText(Environment.NewLine);
var bw = new BackgroundWorker
{
WorkerReportsProgress = false,
WorkerSupportsCancellation = true
};
bw.DoWork += (obj, ev) =>
{
while (!cancel)
{
// Ping Server Here
string response = Server.PingServer();
this.Invoke(new UiMethod(() =>
{
responseBox.AppendText(response);
responseBox.AppendText(Environment.NewLine);
}));
}
};
bw.RunWorkerCompleted += (obj, ev) =>
{
this.Invoke(new UiMethod(() =>
{
responseBox.AppendText("Stopped pinging the server.");
responseBox.AppendText(Environment.NewLine);
startButton.Enabled = true;
stopButton.Enabled = false;
}));
};
bw.RunWorkerAsync();
}
delegate void UiMethod();
private void startButton_Click(object sender, EventArgs e)
{
StartPinging();
}
private void stopButton_Click(object sender, EventArgs e)
{
responseBox.AppendText("Cancelation Pressed.");
responseBox.AppendText(Environment.NewLine);
cancel = true;
}
}
public class Server
{
static Random rng = new Random();
public static string PingServer()
{
int time = 1200 + rng.Next(2400);
Thread.Sleep(time);
return $"{time} ms";
}
}
Erwin, when dealing with C# - threads and UI elements usually you will come across cross-thread operations i.e. Background thread with UI threads. This interaction needs to be done in thread safe way with the help of Invoke to avoid invalid operations.
Please look into below resource: InvokeRequired section.
https://learn.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-make-thread-safe-calls-to-windows-forms-controls

DownloadFileAsync is blocking my App

I am trying to download a large file(around 1GB) my server.When I start downloading I am unable to use the app till the download completes. It is blocking the UI and its becoming unresponsive.
In below code I am calling DownloadFile method when the user download button on the UI.And then download starts, but the UI is freezed.
I read that DownloadFileAsync won't block the UI. But here its blocking. How to use it in correct way. There are several answers but none is working when I am testing.
Code:
Button call:
private void Button_Click(object sender, RoutedEventArgs e)
{
Debug.WriteLine("1");
DownloadGamefile DGF = new DownloadGamefile();
Debug.WriteLine("2" + Environment.CurrentDirectory);
DGF.DownloadFile("URL(https link to zip file)", Environment.CurrentDirectory + #"\ABC.zip");
Debug.WriteLine("3");
}
Download code:
class DownloadGamefile
{
private volatile bool _completed;
public void DownloadFile(string address, string location)
{
WebClient client = new WebClient();
Uri Uri = new Uri(address);
_completed = false;
client.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgress);
client.DownloadFileAsync(Uri, location);
}
private void DownloadProgress(object sender, DownloadProgressChangedEventArgs e)
{
// Displays the operation identifier, and the transfer progress.
Console.WriteLine("{0} downloaded {1} of {2} bytes. {3} % complete...",
(string)e.UserState,
e.BytesReceived,
e.TotalBytesToReceive,
e.ProgressPercentage);
}
private void Completed(object sender, AsyncCompletedEventArgs e)
{
if (e.Cancelled == true)
{
Console.WriteLine("Download has been canceled.");
}
else
{
Console.WriteLine("Download completed!");
}
_completed = true;
}
}
Please refer to this link. The actual problem is getting lots of feedback about the number of bytes downloaded(about progress of download process). Take a timer to get progress for every 2 seconds or any time, this solved the problem.

BackgroundWorker not starting again when once finished

I have a WinForms application which uses a backgroundworker for downloading images from given urls. For the download I use a backgroundworker.
The application is running fine when started, and the download happens as planned, but when the worker is done and I click the downloadbutton again to start downloading from another url, the backgroundworker doesn't do anything.
I fixed that problem temporarily by calling application.restart() when the worker is done, which works but can't be here longer than it has to.
Worker-Code:
// initialization of worker is done in constructor of my class
downloadWorker.WorkerReportsProgress = true;
downloadWorker.WorkerSupportsCancellation = true;
downloadWorker.DoWork += new DoWorkEventHandler(worker_doWork);
downloadWorker.ProgressChanged += new ProgressChangedEventHandler(worker_progressChanged);
downloadWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_runWorkerCompleted);
// ...
private void worker_doWork(object sender, DoWorkEventArgs e)
{
WebClient downloadClient = new WebClient();
HttpWebRequest HttpReq = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response;
try
{
response = (HttpWebResponse)HttpReq.GetResponse();
}
catch (WebException ex)
{
response = (HttpWebResponse)ex.Response;
}
if (response.StatusCode == HttpStatusCode.NotFound)
MessageBox.Show("Website not found");
if (response.StatusCode == HttpStatusCode.OK)
{
for(int i=0; i<3;i++)
{
string image = getImageUrl(url,i);
downloadWorker.ReportProgress(i);
image = WebUtility.HtmlDecode(image);
string saveName = "img_"+i+".png";
try
{
downloadClient.DownloadFile(image, saveName);
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace);
}
}
}
}
private void worker_progressChanged(object sender, ProgressChangedEventArgs e)
{
rtxtStatus.AppendText("Downloade Image" + e.ProgressPercentage + " of 3");
}
private void worker_runWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Download completed");
}
edit:
if (e.Error != null)
{
MessageBox.Show(e.Error.ToString());
}
To avoid any misunderstandings: The backgroundWorker is definetely running at the second time, and it is not an error of the reportProgress-method, since I get the same thing when I dont report anything.
edit no. 2:
I found out where the error came from: at the second run, the for-loop is completely skipped. But that doesn't make any sense for me either... There can't be any other value still be in because I have a completely new instance of the class, can it? But anyway, if it just skipped the method the worker still should exit which it doesn't do. For testing, I added a MessageBox after the for-loop, which is not executed after the second run.

Background Worker is called twice

I have a problem with background worker, it gets called twice thus, increasing the time of execution for my long routine, I created background worker manually so, there is no chance for the DoWork to be initialized within the initializeComponent() method, any help is appreciated.
here is my code:
// constructor
public TeacherScheduleForm(Therapist therapist)
{
this.therapist = therapist;
InitializeComponent();
bw = new BackgroundWorker();
bw.WorkerSupportsCancellation = true;
bw.WorkerReportsProgress = true;
bw.DoWork += bw_DoWork;
bw.ProgressChanged += bw_ProgressChanged;
bw.RunWorkerCompleted += bw_RunWorkerCompleted;
load = new LoadingForm();
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
load.AppendProgress(e.ProgressPercentage);
// load.AppendText(e.ProgressPercentage.ToString() + "%");
Console.Write("Progress: " + e.ProgressPercentage);
// MessageBox.Show("Progress : " + e.ProgressPercentage);
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if ((e.Cancelled == true))
{
MessageBox.Show("Cancelled");
}
else if (!(e.Error == null))
{
MessageBox.Show("Error : " + e.Error);
}
else
{
updateUI();
load.Close();
Console.Write( "Done!");
}
}
// do work of background worker
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; (i <= 2); i++)
{
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
else
{
// Perform a time consuming operation and report progress.
Console.Write("Before Doing work");
setup(therapist.therapistID + "", schoolYear);// the time consuming operation
Console.Write("Doing work");
//System.Threading.Thread.Sleep(100);
worker.ReportProgress((i*5));
}
}
}
The background worker is called when the user selects the school year through a combo box which is in this code below:
private void comboBoxSchoolYear_SelectedIndexChanged(object sender, EventArgs e)
{
//load = new LoadingForm();
schoolYear = int.Parse(comboBoxSchoolYear.SelectedValue + "");
try{
if (!bw.IsBusy)
{
bw.RunWorkerAsync();
load.ShowDialog();
}
else
{
bw.CancelAsync();
}
}
catch(Exception ex)
{
Console.Write("Error : " + ex.Message);
}
}
You are loading the form after creating the event-handler. Thats the only point I can think off doing the trouble. Try to load the form first and then create the handler.
Reason: At InitializeComponent(); the IndexChanged normally will fire up because the control is set at this point with its index. I havnt noticed this behaviour on FormLoad till now. But as I cant see any other problem in here its worth a try.
IF this doesnt solves it, you should also take care if TeacherScheduleForm is being called twice.
Something handy for debugging-purposes:
MessageBox.Show((new StackTrace().GetFrame(0).GetMethod().Name));
Paste this into your event/method or whatever. It will popup a messagebox with the method-name which called your current method. In this case (from comments) it would've raised 2 messageBoxes saying TeacherScheduleForm for both.
I've saved this to my code-snippets.

RunWorkerCompleted firing too fast

i got some really simple code, but cant get it to work. I'm using BackgroundWorker. Problem is that RunWorkerCompleted is fired way to fast. Instantly after running i get message "Work completed", but application remains frozen for couple of seconds as 'DataType data = new DataType(path);' is beign executed. After that i got all my DataGridViews etc filled correctly. If i swap this single line with Thread.Sleep everything seems to work well. Any ideas?
public frmWindow(string path)
{
InitializeComponent();
DataType d;
backgroundWorker1.RunWorkerAsync(path);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string path = e.Argument as string;
DataType data = new DataType(path);
e.Result = data;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
d = e.Result as DataType;
MessageBox.Show("Work completed");
}
How about you use Debug.Write instead of MessageBox.Show with timers to show when the Methods are entered and exited.
While it is possible for this same background thread to act on your UI, its almost always NOT a good thing to do--UI is not threadsafe.
BackgroundWorker backGroundWorker1;
public frmWindow(string path)
{
InitializeComponent();
DataType d;
backGroundWorker1 = new BackgroundWorker();
backGroundWorker1.DoWork += (s, e) =>
{
System.Diagnostics.Debug.Write("Work started at: " + DateTime.Now + Environment.NewLine);
string path = e.Argument as string;
DataType data = new DataType(path);
e.Result = data;
};
backGroundWorker1.RunWorkerCompleted += (s, e) =>
{
d = e.Result as DataType;
System.Diagnostics.Debug.Write("Work completed at: " + DateTime.Now + Environment.NewLine);
};
backGroundWorker1.RunWorkerAsync();
}

Categories

Resources