Friday, December 9, 2011

ApplicationContext to run background task

Many of times we need to create an application which need to run in background and doesn’t require a form or a GUI. We have an option of creating a Windows Service but sometime it’s difficult to use it for a normal user. So in this situation we have an option of creating an application by inheriting a ApplicationContext class which is available in Windows Form.

To create a project to run a background task we can perform following steps

  1. Create a new Windows Form project
  2. Delete the available Forms and Application class.
  3. Create a new class which will inherit ApplicationContext where we can perform background task.
  4. Create a new module which will contain main method to run the application.

Below is a simple example where we are inheriting ApplicationContext class. In the constructor of class we are starting a new thread where we can perform some long running task and when the task get completed we can call ExitThread which will close the application.

Public Class CustomApplicationContext
Inherits ApplicationContext

Public Sub New()

th As New Thread(AddressOf StartBackgroundTask)
Catch ex As IOException
End Try
End Sub

Private Sub
'Some background Task
For i As Integer = 0 To 5

'Task completed. Close the application
End Try
End Sub
End Class

We also have to create a new Module which will contain Main method to start the application using Application.Run and having CustomApplicationContext class as it’s parameter.

Module MainModule
Public Sub Main()
Dim context As New CustomApplicationContext
End Sub
End Module

Download Code: CustomApplicationContext.rar

No comments:

Post a Comment