Threaded console app not exiting upon completion - c#

I wrote an integration program that fetches data from an ERP and sends it to another program via a SOAP API.
In order to determine which data needs to be updated or created I'm also fetching the data from the SOAP API and building some custom early bound entities with that data using
records.AsParallel().ForAll(record =>
{
var acc = new Account(connection, record.name_value_list);
accountList.Add(acc);
});
Task.WaitAll();
I'va added the last instruction after having seen that the programs hangs upon completion and I have to close it manually (and it still lags 5-10 seconds when I do it).
I tried to add an additional wait condition in my Main as the last operation, but it does not help.
I debugged the app and in the Thread panel I see this:
How can I manage to exit my application gracefully?

I found the problem: I was retrieving the data from the ERP via a C++ DLL Api, but I was missing the closing of the connection at completion.
Once I did that the program closed correctly.

Related

Migrating polling to SignalR without polling on the server?

I have a piece of functionality in my web application that kicks off a long running report on my server. Currently, I have an ajax method on my client that is constantly running to check if the currently running report is complete. It does this by repeatedly calling a method that queries the database to determine if a given report's status has changed from Running to either Error or Complete. Once the report is finished, I perform an ajax load to get the data.
I'm looking at implementing SignalR to add some additional functionality to other pages, and I figured this would be a good test case to get things going. My main concern is how to alert the client when the report is complete. Using SignalR, I can simply say something like:
public class ReportHub : Hub
{
public async Task ReportComplete(string userId, ReportRunStatus guid)
{
await Clients.User(userId).SendAsync("ReportComplete", guid);
}
}
However, I want to try to avoid putting a long running loop on the server as I'm afraid this could degrade performance as operations scale up. Is there a better way to handle checking the report status and alerting clients than simply polling until completion? Or is there some easy way to constantly be looking at the table and alerting on completed reports?

Synchronization between GUI Updating thread & processing thread

I have developed one application in which i am continuously sending request and reading response at serial port and updating huge GUI comprise of zed graphs, objectlistviews, analog meters.
Currently i am using one thread which is performing request & response at serial port and pushing the data into queue , and another thread which is fetching data from queue and updating the GUI.
for this i am making the use of Autoresetevent(Set and waitone) for notifying the GUI thread when data is available in the Queue.
This is actually sequential operation so whatever data comes at serial port should be immediately updated into GUI. Something like below model
1 Response -> Update GUI -> 2 Response -> update GUI -> 3 Response -> update GUI -> so on ..
Whenever i get any error at the serial port complete model get mess up and GUI is not updated properly.
Can anybody please let me know what approach should be implemented for achieving the above?
As English is not my first language, let me know if anybody needs further improvements in the question.
.net framework 3.5 SP1 and VS 2008
sent methods can be called from gui thread, it is OK. Problem is on receiving. You can simply set checkforillegalcrossthreadcalls to false and directly call main (gui) thread method within serial port's datareceived method. However I would not use this method.
I would prefer calling a delegate method to update GUI.

Cancellation of a long running task in C#

I am working on a project where we have lots of separate components are running and my agenda is to cancel the component process in between based on user input.
For example: I have 6 windows service that do all the work and 1 another windows service that is responsible for distribution of work. so once the work is send to worker windows service there is no control over it. this worker windows service do some time consuming task, calling several function, interect with database etc. I want to cancel the task in between of working.
The traditional approch we use for cancelation will no longer work here as...
1. I am not iterating any loop where I can continuosly check for Cancel flag.
2. Since the component is totally separate and once they start working, new instance is created of that component and not able to pass any value to that component.
Thanks in advance.

Can a button be used to run cpu intensive code and then display the results using c# and asp.net for a web app

I am currently trying to create an application which has a homepage. On this homepage there is a button which is going to run CPU intensive code and then display the results. As I stated in the title the application is using ASP.NET and C# not Windows Forms which some other websites I have looked at seem to suggest.
I am relatively new to C# and have not attempted this in any other programming language. I also have no code to show as I don't really know how to progress this.
It can run CPU intensive code on the server, yes. Note that this will typically block your web application from sending a response in a reasonable amount of time and the web application could appear to be frozen.
What type of CPU intensive code did you have in mind? There are many ways to handle this scenario.
By "CPU intensive" I assume you mean it will take a long time for the process to complete? In a web application anything that takes more than a few moments should be done asynchronously. In the request/response model of HTTP it's best (for a number of reasons) to respond quickly to a client making a request.
In the case of a long-running process, by "asynchronous" I do not mean using AJAX, as that's still a request/response like any other.
By "asynchronous" what I mean in this case is that you want to have a separate server-side process which handles the CPU intensive task, and the web application does nothing more than queue the task for running and check the status of the task when people look for it. Then it can report the results of the task after it's done.
So a basic overview of the architecture would be something like this:
A user in the web application clicks a button to "start the task."
The web application inserts a record into a database table indicating that the task has been queued (maybe with a user ID of who queued it, a time stamp, anything else you'll need to know).
A separate scheduled application (console application or Windows Service, most likely) is perpetually running. (Either using a timer in an always-running Windows Service or scheduled to run over and over, such as every few minutes, as a console application.) This application checks the database table for new queued tasks.
When the application sees a task, it marks it as "started" in the database (so subsequent runs of the application don't try to run the same task in parallel) and starts running it.
The web application can see the status of the task in the database table and display it to users who request it, so users can see that it's still running.
When the task is completed, the task record in the database table is updated and the result is stored somewhere. (Depending on what the result is. Data? In the database. A report file of some sort? Save as a file somewhere. That's all up to you.)
The web application can see the status of the task as completed and any other information recorded, and users can request to view the output of the task.
The main thing to remember here is to break up the responsibilities into two applications. The web application is for the purpose of providing a user interface. A web application is not suited for long-running background tasks. So that responsibility is moved to a separate application which is better suited for that purpose. The two applications coordinate via a shared database.

Debugging of WinRT's background networking

I've made a project than uses tcp sockets connectivity (own closed protocol), added background connectivity with Network Trigger API, as described here (starting from page 17) - StreamSocket control channel registration block, and IBackgroundTask class, that should be fired each time socket receives something.
Have tried everything to debug the code in background task, with no use:
closing the visible app with a gesture
lock the screen
tried to load some other heavy application, to make windows suspend my app
All these have not helped me to make background task run (and debug) during socket message. What am I doing wrong? Should I have to get the separate suspendable device, like a WinRT tablet, to get this working?
By default referenced projects are not added to the main one. This is not so obvious as it may seem, and that's why I spent almost a week to find out this. So the clue is: check reference projects accessibility.
Upd:
There are some more things to deal with, as I've found out during development. Some of them are not as clear as they need to. Here is a list of what I did:
Add background project to main project's references (right click on references node in solution browser).
Check if main project manifest contains right declaration (background task w/control channel, right background entry point name with full package, $targetnametoken$.exe as executable)
A thing that leads from #1: all the entities you plan to use within background, should be put into separate project in solution. This project is then referenced by both main and background projects.
Be aware of BackgroundExecutionManager.RequestAccessAsync() to be called before registering ControlChannelTrigger
A key thing I've found just in one small comment in a sample project:
// IMPORTANT: When using winRT based transports such as StreamWebSocket with the ControlChannelTrigger,
// we have to use the raw async pattern for handling reads instead of the await model.
// Using the raw async pattern allows Windows to synchronize the PushNotification task's
// IBackgroundTask::Run method with the return of the receive completion callback.
// The Run method is invoked after the completion callback returns. This ensures that the app has
// received the data/errors before the Run method is invoked.
// It is important to note that the app has to post another read before it returns control from the completion callback.
// It is also important to note that the DataReader is not directly used with the
// StreamWebSocket transport since that breaks the synchronization described above.
// It is not supported to use DataReader's LoadAsync method directly on top of the transport. Instead,
// the IBuffer returned by the transport's ReadAsync method can be later passed to DataReader::FromBuffer()
// for further processing.
More info here - http://code.msdn.microsoft.com/windowsapps/ControlChannelTrigger-91f6bed8/sourcecode?fileId=57961&pathId=2085431229
If you did all things properly, the debugging of background tasks is straightforward. Just put the breakpoint and go on, nevermind of main project is running or suspended.
ps - If the project is suspended, be aware of calling UI thread (especially awaited things) - they won't run until app is running, and will wait.

Categories