Conditional statement to avoid concurrent Webclient IO thread - c#

I am using a webclient to download a media file from my web server and save to isolated storage.
If you click a button it starts the download and save to Iso store process, but if you click the button while the file is downloading it tries to create a concurrent IO thread to download again and errors with webclient does not allow concurrent IO threads.
I want to write a conditional if statement to check if there is already a IO thread in being used but I'm not sure how I would do this.
Any help would be greatly appreciated.

Can't you just use a boolean to see if you started the download already? Either way it sounds like it would be better to actually disable the button in the UI after you start a download, and enable it again once it finishes or fails.
Your UI should be consistent with what users have the ability to do at a given time - letting them try something and then make them fail sounds like a frustrating user experience.

Related

Is there a way to monitor the state of a console application?

Is there a way to monitor the state of a console application?
I am trying to build a user interface which shows whether or not a console application is currently running on the server (processing files). If it is running, I would like to show the current state: how many files processed, what file currently being processed, etc.
The only way that I can think of doing this:
Create a text/xml file when application is started
Update text file with information about current state for each object it processes
Delete text file when the application is finished processing
To me, this doesn't seem like a very good or efficient way to do it. Is there a way to detect if the ClickOnce application is running, and perhaps some other way to access the "Messages" or Log of it to show the progress?
Note - I am also looking into using NodeJS to do this, but unsure if it has this capability.
First, you should consider writing this as a Windows service instead of a console application.
That said, scraping a log file that your application is writing is a reasonable approach. Just ensure that it never gets too big.
Alternatively, you could look at using custom performance counters. That would open the door to using System Monitor/perfmon as your monitoring tool, so no need to write any client code.
There are at least two ways to achieve that:
Your console application writes some logs, some state files, during its run, so other processes can read those files and understand what is going on in that console process.
Implement an IPC mechanism. There are different ways to do that. It may help you look in What is the easiest way to do inter process communication in C#?.

Windows Phone Resource Intensive Task exiting

I'm writing a Windows Phone application, and it needs to download very large mp3 files, and save them to isolated storage. I've got all the code for this working, and I tested it with smaller files, but now using the actual files and monitoring what the code is doing using the debug output, I've realized that the threads are actually exiting half way through downloads, and files never actually finish downloading.
Is there a reason for this happening, and if so, what can I do to prevent this?
How long does it timeout after? If you are using HttpWebRequest to download the file, the default time out is 100,000ms (100 seconds). This can be changed as simply as inserting:
HttpWebRequest.Timeout = 10;
Obviously setting your own timeout (in milliseconds!) and attaching it to your WebRequest :)
If your not using HttpWebRequest, let me know what you are using and i'll try my best to hep you out :)
WP's internal memory and process management takes care about this. If you spawned a thread from your app which downloads a lot of data in the background OS will drop it off when those resources (by most chance memory) becomes needed for other processes.
You can do two things, depending on your approach for download:
To periodically save buffer chunks in IsolatedStorage when buffer reaches certain size, thus limiting memory usage of the thread.
Implement download thread as BackgroundTask, which should allow "endless" execution.

FileSystemWatcher and write completion

I am implementing an event handler that must open and process the content of a file created by a third part application over which I have no control. I am warned by a note in "C# 4.0 in a nutshell" (page 495) about the risk to open a file before it is fully populated; so I am wondering how to manage this occurrence. To keep at minimum the load on the event handler, I am considering to have the handler simply insert in a queue the file names and then to have a different thread to manage the processing, but, anyways, how may I make sure that the write is completed and the file read is safe? The file size could be arbitrary.
Some idea? Thanks
A reliable way to achieve what you want might be to use FileSystemWatcher + NTFS USN journal.
Maybe more complicated than you expected, but FileSystemWatcher alone won't tell you for sure that the newly created file has been closed
-first, the FileSystemWatcher, to know when a file is created. From there you have the complete file path, and are 1 or 2 pinvokes away from getting the file unique ID (which can help you to track it during its whole lifetime).
-then, read the USN journal, which tracks everything that occurs on your drive. Filter on entries corresponding to your new file's ID, and read the journal until reaching the entry with the 'Close' event.
From there, unless your file is manipulated in special ways (opened and closed multiple times by the application that generates it), you can assume it is safe to read it and do whatever you wanted to do with it.
A really great C# implementation of an USN journal parser is StCroixSkipper's work, available here:
http://mftscanner.codeplex.com/
If you are interested I can give you more help about USN journal, as I use it in my project.
Our workaround is to watch for a specific extension. When a file is uploaded, the extension is ".tmp". When its done uploading, it's renamed to have the proper extension.
Another alternative is to have the server try to move the file in a try/catch block. If the fie isn't done being uploaded, the attempt to move the file will throw an exception, so we wait and try again.
Realistically, you can't know. If the other applications "write" operation is to open the file denying write access to everyone else then when it's done, close the file. When you get a notification then you could simply open the file requesting write access and if that fails, you know the operation isn't complete. But, if the "write" operation is to open the file, write, close the file, open the file again, and write again, etc., then you're pretty much out of luck.
The best solution I've seen is to set a timer after the last notification. When the timer elapses, try to open the file for write--if you can, assume the "operation" is done and do what you need to do. If the open fails, assume the operation is still in progress and wait some more.
Of course, nothing is foolproof. Despite the above, another operation could start while you're doing what you want with the file and cause interaction problems.

multi threading on asp.net

I have not used multi threading much for asp.net. I have a web application that uploads a large temp file to folder. I would like to take that temp file and do some other things with it after it is uploaded. Can I do this work on another thread without the user being on the website any more? Thanks for any help or suggestions.
1.User post large file
2.uploading temp to server
3.After upload completes. I would like to run another thread/worker that can run without any user iteration but is trigger by the user.
void uploading(){
//Uploading file To server
}
void Submitclick(){
Start a Thread
Thread thread = new Thread(DoThreadWork);// does the user still need to be logged in?
Send to another page
}
void DoThreadWork(){Do this in background}
It's definitely possible, I've used background threads quite a bit in ASP.NET to do some funky stuff. If you have complete control over the server it might be more elegant to run the background code in a separate application or a windows service.
It's a better separation of concerns to have your IIS app dealing with just responding to web requests, and it's not geared up for that.
Also a warning, if you have a background thread in ASP.NET 2.0 and it has an unhandled exception, the default is to reset the application pool.
More information here: http://blogs.msdn.com/b/tess/archive/2006/04/27/584927.aspx
// 3 downvotes?
Listen, it's not alway possible to avoid running something in a background thread. I've hit this in several situations:
I've worked in a company with an unreasonable attitude to software
where we were not allowed to deploy a separate app to handle the
background processing. I argued for a windows service, but was
overruled and told to implement it in a background thread. Obviously
I moved on from that company to a healthier environment, but that is
the reality is this you have to deal with unreasonable situations
sometimes.
if you're in a hosted environment you don't always have the option to offload onto a seperate process.
The question was if it is possible. I'm answering that question.
If you want to separate the uploading of file from website user interaction you can make a windows service that will contineously check that if file is ready for upload and upload the file.
You can use the thread pool for that. The sample code relies on the article in the following lik: http://msdn.microsoft.com/en-us/library/3dasc8as(v=vs.80).aspx
First write your method that does the work. The method must get 1 argument of type object:
public void DoWork(object threadContext)
{
}
than, in the place of the code that you want to call the method do:
...
var threadParam = ... // Put any value you want to be used by the DoWork method
ThreadPool.QueueUserWorkItem(DoWork, threadParam );
The method will be queued until the system will hav free thread to handle the work and execute the method regardless if the request has been ended or not.

best way to write a polled FTP download in C#

I currently have a manual process where we upload a text file to a business partner, they have an automated process which reads in the file, processes it and then generates a 'results' log file any where from 3-10minutes (typically) after the initial upload. I need to automate this process via a .NET application.
I already have the upload completed, what I do not have is the download of the result. Since I dont know exactly when the file will be ready to download I figure that I must need to poll the remote site every so often, get a listing of the files in the results directory and see if one matches what I am expecting.
I have done some reading and found some references to AsyncCallBack but I'm not really sure how to proceed with it. the solution has to be something I can manage without any third-party libraries outside of .net since I have a budget of 0 for this little project.
Any help would be greatly appreciated!
Just have a thread (or your main thread) sleep for x milliseconds and attempt to do the download when it's not sleeping. No need to buy a 3rd party FTP library, FTP is built into .NET (FtpWebRequest and FtpWebResponse). They aren't very good (very bare bones) but will probably do for what you want.

Categories

Resources