Does VB.NET perform any multi-threading on its own? - vb.net

I know .Net and C# pretty well, but never even looked at VB.
My problem is: our Win32 COM library is used by a number of clients, and we see that the number of failures is higher for those who use the library from VB (both VB and VB.NET) than for those who use C++, C# or Delphi. One thing about our library is that it is supposed to be used from one thread only - can some threading magic by VB be the cause of failures?
Clients tell us the do not create any extra threads on their own.

VB.NET = C# with a little different syntax. Seriously, you can translate VB.NET into C# line-for-line 99% of the time. Neither language creates threads under your nose without you knowing about it.
At most, if your clients are using VB.NET with Option Strict Off, then VB.NET's late-binding can cause more problems than it fixes -- its hard to know for sure without seeing the actual exceptions you're clients are reporting. In any case, chalk your clients failures up to less skillful programmers and bugs in their own library, not to your code or Microsofts implementation of VB.NET.

By magic, no. VB.Net will not do any extra threading under the hood. In this respect it's the same as C#.
VB6 and earlier can impact threading because all of it's objects will be STA COM objects. This won't add any threads to your program, but merely restrict the manner in which the VB6 objects can be accessed.

One case is Finalize methods. The CLR calls them from background thread(s) associated with the garbage collector part of the system. Most likely, your users should just not be calling your component from within Finalize.
Also watch for the BackgroundWorker or delegate BeginInvoke. Although the user does not create "any extra threads on their own", these mechanisms executes code on a thread pool thread separate from the main GUI thread.

Related

Use of MFC in a COM server - what are my options?

Visual C++. I have to implement some drawing and printing functionality that will be incorporated into (other developers') COM dll. Firstly I thought of doing everything using pure GDI and nothing more, but it seems that printing and print previewing is hell of a job to be done in GDI compared to the MFC implementation. So I decided to focus on MFC. Quick side question here: Is my choice right? I mean, are any easy ways of implementing printing (and print-preview) without MFC?
Now that I need MFC (assuming if you also agree with this), I have two questions about how to do it:
1) I believe the COM dll is the ATL project (it's not my code, some other developers independently develop it). Can I enable MFC support in that dll? What are the risks/limitations/drawbacks of having MFC runtime in the COM server? And if you advice doing this, how can I do it?
2) As much as I want to affect the third-party COM server's code as little as possible, I thought it might be the better approach to implement my code as a separate MFC-based DLL, and load and use that DLL from COM server. Do you advice doing this? What are the risks/limitations/drawbacks in this situation?
Shortly, I want to use MFC's drawing and especially printing capabilities in my code, which itself should be integrated in another developers' COM dll (which itself is utilized in a large corporate application). I'm no expert in COM technology so I'm a little bit confused. What are my best options?
You can use MFC in your own dll internally, and expose functionality to your users with non MFC intruded function: for example if you need to pass a point from/to ypur caller, use the GDI standard POINT structure, then convert it to a CPoint to use internally. In this case you don't need to enamble use of MFC in the ATL project ( that is possible anyway ) but of course you need to distribute or link with the MFC dll. If you want mantain the caller com dll as clean as possible, you can definitely create your own ATL+MFC dll and expose your functions via com interfaces too, but keep in mynd to avoid put MFC related objects in the interface.
Printing and print preview is a hell of a job unless you're using MFC Document/View Architecture. Will your COM expose such advanced UI?
If your COM must be independent of .NET then MFC is the way to go, otherwise I would use .NET. If you choose MFC, make sure you link to it statically. Otherwise you will most likely end up with runtime errors on machines where the necessary MFC version is missing.
Except for this, I wouldn't worry about compatibility since the idea of COM is to let the underlying magic do the marshaling of integers, strings and other objects.

.NET out-of-process COM objects sharing static instances in API calls

It's hard to explain our situaction.
We have a 3-tier application. The engine is a DLL coded in C++, then we have a VB6 ActiveX EXE that access to the engine via API calls, and at the top level we have a Excel Addin (in C# using VSTO framework) calling the middle layer with an interop DLL. At this time, each "connection" from the Addin to the engine creates a new EXE (VB6 uses API calls to access to the engine) and all works fine.
Now we are moving the middle layer to .NET, it works 'presumably' fine (it pass all our Unit test) but, we found an error when we open 2 "connections" at same time (ups, no unit test check this situation because it's a new behavour). The DLL have static objects that it's shared over all instances in the same process and we have interactions between "connections". In our old version each "connection" creates a new EXE with no memory sharing between processes, now it's the same process and they share memory and the static objects.
Following the tips from this question. We tried to build a COM EXE in C# to do an out-of-process objects in the middle layer but we have the same result. They share the static objects, at the end, each connection not creates a independent process.
It's clear, but not affordable at this time, moving API calls to ATL or changing the static objects to instanciable references with a handle and change all the API calls to get/set this handlers. I reviewed all examples in MS All-in-one but I didn't find any solution. Neither it's possible to keep only one connection at time, each workbook can have one connection and in the future we want to explore a Web application with multiple connections at same time.
Any suggestion?
Thanks in advance,
Whether COM starts new EXE per each COM object, or uses single EXE to instantiate all the object is controlled by flags parameters passed to CoRegisterClassObject. See
http://msdn.microsoft.com/en-us/library/ms693407(v=vs.85).aspx, and
http://msdn.microsoft.com/en-us/library/ms679697(v=vs.85).aspx
You need to pass REGCLS_SINGLEUSE or REGCLS_MULTI_SEPARATE flags.
Now, the trick is to pass this flag, as you might not call this method directly - the details depend on how you implemented the COM EXE.
it's not clear from the question, but it sounds like the "middle layer" you have was built as a VB6 EXE, and you're trying to replace it with a .net DLL. If that's the case, you'll definitely get the behavior you describe.
With a VB6 EXE com project, instantiating a new object starts a new process. With a .net dll (or a Vb6 dll really) you +won't+ get a new process.
You'd either need to create a .net EXE that exposes COM objects just like your VB6 exe does, or (sounds like you've already investigated this) you'll need to refactor your EXE objects to properly handle multiple instances within a single process.
Honestly, it'd probably be better to do that latter, since relying on singletons like this is generally a bad code smell. But it a pinch, you should be able to replicate the behavior of the VB6 exe with a .net project. You just can't do it in a dll.
Was your middle layer created in .Net? If it was, you might be facing the issue that your COM class is been created as a native .net object instead of a COM object. The solution usually involve using Primary Interop Assemblies. Take a look on this SO question to see if it matches your problem.

Windows Script Componets - Are they thread safe

I need to develop a very simple class developed as a Windows Script Component that needs to work in a multi-threaded environment.
I am wondering just how thread safe Windows scripting Components are and the scripting engine that executes those components.
In VB6 if a compiled DLL was not compile with "Retain In Memory" and "Unattended Execution" set definately caused problems in a multi threaded environment, I experienced this 1st hand and spent weeks trying to locate the issue with a 3rd party DLL.
Would anyone happen to know what way Windows Scripting Component works, are they intrinsically thread safe (once we don't do anything non-thread safe in the components we write).
I realize that the Windows Script Components are COM Apartment threaded and may not be the most performant things in the world but I have no choice about this.
Kind Regards
Noel
we're found under exterme load testing that WSC components are perfectly thread safe.

What is "DefInstance" and should I remove it from a WinForms app?

I am working on a VB.NET WinForms app that was "upgraded" by Visual Studio (originally 1.0 or 1.1) from VB6 code (which was itself upgraded from VB5). Except for the few new forms I've created since taking over maintenance of this app, all of the forms in the application have a method called DefInstance which allows you to grab an in-memory copy of the form if there is one. What I can't figure out is why: when would I ever need to reference a form object in memory when it's not immediately in scope where I'm working. To my mind this violates all kinds of sound programming principles and seems like an invitation for memory leaks or worse.
The questions: (1) is this DefInstance thing an merely unfortunate remnant of the VB6 heritage of this app, and (2) should I make a point of removing DefInstance methods throughout the application?
I received this answer from a Microsoft employee:
http://msdn.microsoft.com/en-us/library/aa289529(VS.71,printer).aspx
In short, DefInstance is a "not best practices" compatibility method for older apps that haven't been made into true .NET WinForms apps. Being a web programmer until earlier this year I had never worked with VB6 "WinForms" applications nor had to deal with the compatibility compromises that the upgrade wizard makes in forcing them into .NET.
Yes, the default instance is a terrible byproduct of importing the application through the upgrade wizard. Using the default instance was a VB habit in pre dot net versions because forms were always resident in memmory as a default instance, although you could also g=create additional instances.
As Parvenu74 said, it is not a best practise. That being said, you should be very careful when removing it from an imported application because of side affects and references where it might be being used. Your best bet is to not use it in new code that you develop and slowly migrate yourself away from the "converted" code over time. As was mentioned above the default instance stuff was re-instroduced in VB 2005, but it's use is highly discouraged.
As you mention, it lets you get a reference to the form.
I've seen lots of VB written like this:
Private Sub Command_Click()
Call DoStuff
End Sub
Private Sub DoStuff()
Form1.myTextbox.Text = "Bad Idea"
End Sub
DefInstance allows DoStuff() to continue working without passing controls around.
See here: http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/6d7985b5-6db6-47a8-9e11-cbf114a48d37/ for more info.
Sadly, that toxic bit of syntactic sugar was added to VB8 (VS2005). Now fatally confusing VB.NET programmers when they can't comprehend that each thread has a separate instance of "Form1". The good news: now you definitely don't need DefInstance anymore.

Best way of Multithreading

I have a college assignment due quite soon, and I need to be able to call a C++ dll that takes a long time (possibly infinte, it relies on user input)to execute. Im calling this through VB. My VB GUI freezes up when this happens, and I would like to keep the GUI responsive, so that the user can stop this possibly infinte loop.
Can anyone suggest the best/fastest way of doing this?
A bit of background, the C++ is trying to keep score on a snooker table using a webcam, and while the VB scoreboard updates easily, I would like to script it so that the analysis is almost continuous, while still allowing the user to interact. Currently the project requires the user to press a button to start the shot analysis, but it would be preferable if the program scripted itself. I have only realised this problem now and the deadline is very soon.
Update: Our lecturer suggested an option to solve the problem, but it would appear that most options here and the one he suggested will not work for us as the processing time required for the webcam image capture is too great to handle due to hardware constraints. Thanks for taking the time to help, it was much appreciated!
The best way to handle threading in VB.NET is via the System.Threading namespace.
You might also look into Application.DoEvents()
Try the system.Threading as Mark said, also try looking at Background Worker Process which is a bit simpler in VB.NET. Readup here
I would definitely use the Background Worker process. You can drag it onto your form and use the DoWork sub routine to actually do the work that is freezing your GUI thread. You can also use the ReportProgress event to actually provide progress back to your form.
As for your question regarding two separate threads, If both steps take a long time to complete I would run them in the same thread one after the other.
The one thing that could bite you with using the thread is cross-threading. In the context of your problem this means not having your second thread update form controls.
A really good resource for how to implement this code along with dealing with cross-threading is this PDF.
I also should point out that if you are using .net 1.0/1.1 you can still do the multi-threading, but don't have the luxary of having a background worker control. You'd just have to create a new thread from the System.Threading Namespace.
Just as an alternative, you could have your C++ actually processing in the background all the time. When called from VB, it would just be retrieving data from it or sending it a command (start, quit, ???) all of which would return instantly.
This could also give you more reliability since C++ would never miss video frames while VB was collecting the garbage or doing the dishes or whatever VB does in the background--C++ is going to let you be closer to a real time system.
RE: the comment about how.
What I'd probably do is have my VB programs send "Messages" to the C++ (As I said). A message is just a way to think of a function/method call--but generally they return quickly.
The "Start" message would tell the C++ code to start it's thread running and return. This is a Linux C++ thread howto, I'm not sure if you need to do something different in windows (I'd hope not, but I haven't used C++ as my main dev. language in decades).
If that doesn't work, just google "C++ Threads"
Sending a "Stop" message would stop the thread (and probably free resources).
A "Get Data" call would go to the location that the C++ thread used to store data, grab it and return.
Sorry to be so general, I'm pretty heavily Java these days.
I'm surprised nobody has suggested using a BackgroundWorker yet.