Multithreading HttpListern resume sleeping thread - c#

I have an HttpListener that for each request received launches a winform and returns an array of byte representing an image. This image is taken by the winform once it executes some commands parsed from request's querystring. Any winforms is executing inside a different Thread.
Right now after the winform has done its job, it comes up with an array of byte as the response and then its thread died, if the same user makes a new request a new thread (with a new winform) is created.
I'm guessing if I can maintain each thread, using an ID for each user (IP address, a GUID, cookie), so I don't have to recreate the winform every time and at the same time the winform will maintain previous state.
Is it possible? Or I have to move to another direction or design?

You could change the design to workers/tasks approach, defining separately the worker pool (thread+Form) and the task pool. That done, you can decide wether to create a new thread/form pair to handle a task or reuse an existing one, you can choose the number of workers to run, limiting the risk of over consuming the server resources. But using Winforms on a server side is definitely not the best way, as shf301 pointed out.

Related

How to make 2 forms on 2 separate threads in C# winform application

I am developing an interface in my C# 4.0 winform application, to fire some sms in bulk. Each message content is different so that I have to fire messages one by one. I have a form from where the end user can shoot smss, it may be more than a thousand.
I want to manage a queue. If the user shoots a sms then it will be submitted to the queue and the queue will send sms one by one.
So I have to create a form to manage the queue. The problem is that I want my application to work normally and in the background the queue sends sms.
So how can I achieve this task? I have tried BackGroundWorker, but I don't know how to maintain a separate thread with a form.
All forms must be on the UI thread. The sending of the SMS should be performed by the BackgroundWorker.DoWork event. The updating of the form is then done by BackgroundWorker.RunWorkerCompleted event.
The UI thread is main thread of the application for SWF (winforms)
If you are using C# 4.0 or above, you may also want to investiage the Take Parallel Library (http://msdn.microsoft.com/en-us/library/dd460717.aspx). But I would first get BackgroundWorker implementation to work. Then use TPL to send simultaneous SMS. Could really speed things up.
you have to create one thread (called worker thread) which runs for the life your application.
you have to have a queue or even better a concurrent queue http://msdn.microsoft.com/en-us/library/dd267265.aspx
the worker thread wait when an item (sms) appears in the queue, takes that item and do its work.
the UI is completely decoupled from that work.
this is most basic use of the class Thread.
Background worker is least suitable solution. obviously you can use a washing machines to build a house but most people use bricks.
You can start Thread then create new instance of form on it (with no parent) and then start message loop (such code located in Main method of project's template).
Remember, any form (generally any GDI object) can be used only on thread that creates it. E.g you can't create child form on another thread, then parent's. Every GUI thread must run message loop.

Single instance C# window that repaints

What I thought would be pretty easy is quickly defeating me. I'm not a native C# programmer, but was asked to create a WinForm application that has a single instance. I''ve seen the Mutex examples already on StackOverflow, but the one thing that eludes me is the ability to pass parameters to window on the command line, parse the values and repaint the form with the new values.
Anyone have an example of this? The main thing that seems to be tripping me up is the threading. I want to run my.exe and show the window. Each time the form is run, I don't want a new form -- just to get the new parameters and show them in the form.
Any/All replies are appreciated!
When you starting another instance of your application, you are running same code, but on different process. So, you need to look on passing data between processes. Something like Named Pipes or Remoting.
#lazyberezovsky is right. Invoking again the application from the command line will spawn a different, unrelated process and you would require inter-process communication to forward the new parameters to the previously running app instance, before quitting the new process being invoked.
IMHO, the easiest way (not the best certainly) to communicate between these two processes would be using the Windows Registry, as this is already thread-safe and the API is very simple.
First, when the application runs, before showing the main form, I would perform a check to see if another instance of the app is running.
If false, it is the first time the app runs and I would process the command line and show the form as regular. I would also clear the registry key used for inter-process communication (see below).
If true, then I would store the command line in the registry on a specific key that will serve for inter-process communication and then I would terminate the application without even showing the main form.
Your running application (the first instance) will require to start a polling mechanism (could be a Windows timer firing once each second) that regularly examines the registry key where a new command line is expected . It would normally find and empty string and do nothing, but if the retrieved value is not empty, then it would mean the user spawned again the application with a different set of parameters, then you can proceed to decode your command line and repaint the window as necessary. After this, make sure you clear the registry entry again, so the polling mechanism resumes and detects the next time the application is invoked by the user.
Named pipes, WCF, .remoting or TCP sockets are IPC mechanisms that can be used and won't require a polling mechanism, that may be frowned upon by some. ;)
Hope this helps!

call a function after function finish

first time poster here!
I'm a Senior Computer Science Student and I'm currently developing a GUI that plays A board game (othello ) online using telnet.
the pseudo is something like this...
click button
update GUI
recieve telnet input
update GUI
rinse and repeat!
the problem is though, the only way i know how get the telnet function to go is by putting it inside the Click event handler, but the GUI won't update until the whole function is finished. Meaning it updates every two moves instead of one. Is there a way to tell C# ( which I'm new to) to call a new function immediatly after one has finished? specifically on a GUI.
any input is appreciated
Thanks
I'm not sure I understood correctly the problem, but the "receive telnet input" line makes me worry a lot.
Are you writing this application in a single thread without using any kind of asynchronous TCP/IP communication?
If the answer is yes, the error is in the architecture you are using.
You need asynchronous tcp/ip communication, for example, with another thread running in parallel, with asynchronous sockets or with asynchronous streams.
You cannot stop the GUI waiting for the network, it would be a bad architecture.
Try to read this simple but complete article on codeproject: http://www.codeproject.com/KB/IP/socketsincs.aspx
Windows OS uses a thing called "message pump" to handle windows. Everything is a message that is processed by a single thread (your application thread).
Events are enqueued in the message queue.
If you stop the execution of the main thread for too long you are stopping the message queue from being processed, and this will stop user input and also painting, since rendering is also a windows message that can be enqueued.
You'll need to use threads. This way while one thread is still processing you can fire off a new thread. I think that's the only way you'll be able to simultaneously finish processing one task while starting up another at the same time.
Once the task is done processing you can join it back to main thread.

Open InternetExplorer COM object to do some automation using Wating from WPF app, but keep UI responsive. is this possible?

I have an app that runs a process which needs to open an internet explorer, go to an url, and do some stuff there, input some data, and return.
This usually takes a while (several pages that need to be filled, doesn't matter). The problem is, while this process is being done, the calling app (a standard wpf app) UI is unresponsive/frozen. When the process returns, i have some info that i need to set in one of the WPF app's objects
The main problem is that since IE needs to be called from within an STA thread, if I try to call it from within the dispatcher asynchronously or synchronously, for some reason the UI is blocked (i have tried with different DispatcherPriority-es but didn't get lucky).
If i start a new BackgroundWorker, that thread is in MTA mode (and i can't switch it back), so there's a problem and i have an exception
I'm really lost here, could anyone put some light into this? maybe what i want to do is simply not possible.
Have you tried creating your own background thread (not relying on BackgroundWorker), and set its ApartmentState to STA?

Handling long page execution times in ASP.NET

I'm working on a web application import program. Currently an admin user can upload a formatted csv file that my page will parse. I'm experiencing an execution duration issue as each line pertains to a file that has to be saved to Scribd, S3, as well as some internal processing.
What would you guys recommend for improving execution time? Since this is an admin only page, I doubt it would get run more than once a week, so my hope is to get it out the door asap.
I've looked some at the Async="true" flag, but I wasn't sure if that was the direction I wanted to go, or if I should look more that a windows server.
Two options come to mind:
Threads: In your code setup a collection of threads, join them and then have each one process a single file. Once all the threads complete you'll be able to return the page. This will increase your turn around time, but could still leave something to be desired on page returns
Queue: Have the user submit the csv file and provide a GUID/Hash/Whatever ID where the admin could then go to the "status" page, input their ID and check the details of their job. This solution will provide a quick feedback to the user and allow them to keep track of the results without having to wait around.
A quick and dirty option might be to set Page.Server.ScriptTimeout to a really high value on that page. (I think it maxes at Int.MaxValue).
Probably advisable to block the submit button after its been clicked, and inform the user that they may want to go make a coffee.
I'd suggest using AJAX to have an internal post back occur that would handle the asynchronous processing. You can periodically poll the state, and prevent your master page from having the "processing" wheel constantly churning on the page for the lengthy process.
I have a web page that takes a long time to process a mailing list so I kick it off in it's own thread. When the process is done, a report can be seen from another link on the result page. I have a runable MailSender class. The ASPX script has a bit in it that looks like this:
// prep the MailSender
MailSender ms = new MailSender(people, Subject, FileName....);
if (SendAsync) {
ThreadStart ts = new ThreadStart(ms.run);
Thread WorkerThread = new Thread(ts);
WorkerThread.Start();
} else {
ms.run();
}
If you want to speed your code up, try to break it into parallelizable pieces if you can and write a class for each piece. You could then kick off a new thread for each bit and monitor the status somewhere so the user can be informed when to come back to the results. You said that each line of your input would generate it's own output file. Sounds like a great candidate for multi-threading. Won't speed things up much if you don't have multi-cores availabe on the server though.
One problem with this whole scheme is that server restarts or application pool recycling will kill your long running process. This can be a problem if you threads are going to run for an hour or two.
As external factors are involved in the processing time, you need to consider if performance improvements would affect "actual" performance, if most of the time is in processing it and sending it to the thirdparty (ie Scribd,S3), then making improvements on your end might not have a huge affect and might increase the complexity for a simple task.
What I would do is have the aspx page only doing what aspx does best; ie handling the user interface part only (ie the upload), so once the upload is complete as far as the user is concerned their part is done. You could implement a progress indicator using AJAX to make it nicer but as its an admin section I wouldnt bother with the niceties,
Then have simple console application sheduled to fire at specific intervals, or a windows service watching a directory (depending on how timecritical the updates are), once the app runs as it is in the back ground and does not require user interaction, time is not a critical factor (ie you dont have a user waiting for context to be returned)..
it will appear to the user that things are very snappy (ie the time it takes to upload the file) and you are keeping needless complexity out of your solution.
I think the simplest solution to what you want is to use asynchronous pages in ASP.NET. Is there any particular reason why you don't want to go that route?
I can think of an alternative, which is to have some background process (like a process triggered by a scheduled task in Windows, or a Windows service) that will look at a queue of waiting jobs (say, from a database table) and process those jobs. This way you will have to upload that CSV somewhere and insert a db record so that the background process will see that CSV and use it when it comes around. But to me it seems like more work, so I'd rather use asynchronous pages :)
Here's a nice tutorial on ASP.NET asynchronous pages

Categories

Resources