How to get JavaScript working using Callback with COM
Imagine you have a scenario wherein you want your COM Server to be called within JavaScript which invokes an Async method. Upon completion of the Async method you would like to notify the JS using callback function that the task has been completed. Doing the Async work is simple but the callback to notify the JS that the task has been completed is tricky. What can we do in such scenarios?
If you are implementing an ActiveX control, you need to create a thread pool when the object initializes or when it receives the first request. Then, each send request would be dispatched to the thread pool and return back to the caller. For example, if we refer to the diagram below, the ActiveX controls equivalent to PrintAsync() would be:
PrintAysnc(CallbackObject)
{
DoWork(CallbackObject) // queue request to thread pool; work is not actually done in this function!
return (); // returns immediately
}
DoWork() queues the request to the thread pool and does not do the work. The thread pool thread then does the work and uses the completion object to signal back to the original caller that the request is done.
An example of code that interops with JavaScript and does an Async work looks like this:
public void MethodCalledByJavaScript()
{
Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
ThreadPool.QueueUserWorkItem((state) =>
{
// do async work here
dispatcher.Invoke(new Action(() =>
{
// call back into JavaScript here
});
});
}
When JavaScript calls into MethodCalledByJavaScript(), it returns immediately and allows subsequent JavaScript code to continue executing, while at the same time spawning a new thread to do the Async work. When the code in the thread finishes executing, it uses the dispatcher to queue a work item on the UI thread to call back into JavaScript.
More info on the Dispatcher class: msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher(v=vs.100).aspx
The Dispatcher class (System.Windows.Threading Namespace) is available in the following Dot Net versions:
Dot Net 3.0 (Base version 2.0)
- Dot Net 3.5 (Base version 2.0)
- Dot Net 4.0 (Base version 4.0)
- Dot Net 4.5 (Base version 4.0)