kheya
kheya

Reputation: 7621

Running a console app programmatically whenever needed

I have a C# console app that processes a queue (in db) and processes user uploaded contents. It is running as a scheduled task.

If some user drops some content, the process won't pick it up until it is time for it to run.

If the job runs once every 5 minutes then it has to wait for max 5 minutes to run. I want to process user content right away.

If user1 drops content and then user2 drops content after 30 seconds, I want 2 instances of my job running.

Is it possible to trigger the job\task to run from the C# code (MVC controller)?

Upvotes: 0

Views: 952

Answers (1)

David
David

Reputation: 219047

Essentially it sounds like you're just looking to perform an asynchronous operation. Depending on the version of .NET, there are a number of options. For example, the Task Parallel Library is a simple way to invoke an asynchronous operation. So if the task is encapsulated into some object (for the same of example, let's say a method called Process on an object called content) then it might look like this:

var processContent = new Task(() => content.Process());
processContent.Start();

The task would then continue asynchronously and flow control would return to the application (which is particularly ideal in a web application where you don't want a user looking at an unresponsive browser, naturally).

If you're using .NET 4.5, you can also make use of the async and await keywords to perhaps make it a little more clear. At its heart, you're talking about running a process in a separate thread.

This all assumes that the web application and the console application share the same back-end business logic code. Which, of course, is probably what they should be doing. If for some reason that's not an option (and I recommend looking into making it an option), you can start a process from code. It could be something as simple as:

Process.Start("C:\Path\To\ConsoleApplication.exe");

Though forking all of these processes can look pretty messy and might be very difficult to manage in terms of error handling/logging/etc. Another reason why it's best to keep the logic in the same process as the application, just in a separate thread.

Upvotes: 2

Related Questions