Method for replacing INVOKE - vb.net

Is there a way around using the Invoke and InvokeRequired methods for objects which were created in other threads? Is there a method which is more direct and less memory intensive? Perhaps a state machine or thread controls?
Am I wasting my time worrying about this method's resource usage?
I'm using this invoke method: http://tech.xster.net/tips/invoke-ui-changes-across-threads-on-vb-net/
I'm using VB.NET in VS 2012

This strongly fits my doctor's usual advice: "if it hurts then don't do it".
There are several .NET patterns that emphasize keeping the threaded code separate from code that needs to run on the UI. BackgroundWorker has been available for a long time, note how its ProgressChanged and RunWorkerCompleted events run on the UI thread. Good place to update UI without having to invoke yourself.
The .NET 4 Task class hands you the TaskScheduler.FromCurrentSynchronizationContext() method. Which is a good way to chain a task that runs on the UI thread, pretty specifically intended to update the UI with the results of previous tasks that run asynchronously. VS2012 provides yet another weapon with the Async and Await keywords. All good ways to avoid writing the code you don't want to write.

Related

How to deal with SQLite in an asynchronous project

SQLite is not asynchronous, and the exposed Microsoft.Data.Sqlite ADO.net *Async methods are implemented synchronously under the hood.
My question: how would you use SQLite in a asp.net core 5 API project which could benefit from asynchronous code, and also the async/await keywords to coordinate it?
I see two options
use the "fake" *Async methods, and lose the benefits of asynchronous code for the code parts that touch the db. If I understand correctly, in .net core blocking a thread will not lead to deadlocks (https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html). If I understand correctly that would act like synchronous code executing on a thread pool thread, with the added overhead of the async/await machinery.
write synchronous code only, and lose the benefits for parts of the code
Which one do you think would be better?
Thanks!
I would tend to use the synchronous Async methods, but it's not a strong preference. The only reason I'd prefer Async is just in case either a different database is used in the future, or SQLite gets real asynchronous methods in a future release.
What you definitely want to avoid is await Task.Run.

VB.Net, specify a thread for BackgroundWorker to use?

This is far-fetched I know but I have to ask. Is there a way to specify the thread that a BackgroundWorker instance is to use? Or at least some way to force it onto another specific thread (whose reference I have). I have a large project that makes use of BackgroundWorker, and I have just recently started using some in-house FRAMEWORK (I have to) that uses Thread instead, and the two seem not be happy with each other (I know the reason but I can not fix it as it is in the framework whose guts I can modify) that is why I ask this question, before I spend days converting my project to use FRAMEWORKS Threading functions.
You might be able to derive from the BackgroundWorker class as it's not sealed and override the methods for RunWorkerAsync etc. Would be painful and easy to introduce bugs, but that would give you the ability to kick off the DoWork event onto your in house thread framework.

Windows Forms Project with Threading

I have read a LOT of material about Windows Form projects not supporting MTA. I get it. However, I also have read about Background worker, async/await and BeginInvoke use with such solutions. This and this are just a couple of examples. Here's one that even uses MSMQ. Some of the examples I have reviewed go way back to VB6 days.
I need to augment a Windows Form project with code to interact with a vendor service via API calls that could benefit from async capability. This being 2014, what is the best way to approach this? I use VB NET and have VS 2010 for my development.
Ideally, I would like to create a class library with the logic to interact with the vendor and just return the results to my Windows Form project. Can that be done?
The fact that MTA is not supported doesn't mean that you can't use multiple threads. The MTA model is just one way to use multiple threads, but because it's difficult to implement objects for that model, Windows Form uses the STA model instead.
The important effect of this is just that it means that the main thread in the application takes care of everything that has to do with the user interface. You can start as many threads as you like/need, but whenever anything from those threads needs to be displayed in the user interface, they have to use the Invoke method to let that update be done in the main thread.
There are already asynchronous method in the framework, for example the BeginRead and BeginWrite methods in the System.IO.FileStream class. You can have a look at those for some hints on how asynchronous methods are used in the framework.
If the API is synchronous, you would make asynchronous methods by simply starting a new thread that does the API call and then executes a callback method when it is done. As it's that thread that is waiting for the response, the call doesn't occupy the main thread.

How are Handlers and Runnables used in Android Programming?

What are Handlers and Runnables used for in Android programming. What is the relationship between them? Also, how does Handlers differ from Threads?
Difference is minor, both are executed in a separate execution flow, i.e. have their own execution contexts. In Android programming, certain instructions should be executed in non-UI thread. For example, networking. That's where Runnable and Handler come to mind. The only important difference is that Handler is supposed to be executed when some asynchronous event happens, whereas Runnable is executed whenever programmer wants it to be executed
No Difference Between them .Handler is a subclass of thread class.
Handler
allows send messages between two threads in a safe manner, that means that sending thread puts message into destination thread queue, and this destination queue will process this message in its appropriate time.
Runnable
this is an interface that you implement, in implementation you put logic you want to execute on some thread. You can actually use Runnable also in non thread related places. Lots of Java apis actually use Runnable, not only Thread's. You can post Runnable using handler, or you can use it with executors. Runnables are nice because you can implement them in a form of anonymous implementation.

How Important is it to use `performSelectorOnMainThread:withObject:waitUntilDone:` From an NSOperation?

My iPad app syncs with an XML feed, running the sync in an NSOperation subclass executed from an NSOperationQueue. As it parses the feed, it calls back to the main thread via performSelectorOnMainThread:withObject:waitUntilDone: to update various parts of the UI, schedule downloads, etc. Some of this is pretty expensive; the UI can sometimes become unresponsive for a second or two as a sync is going on.
To make the UI more responsive, I've removed the use of performSelectorOnMainThread:withObject:waitUntilDone: in favor of direct calls to perform all the sync-related tasks, including updating the UI. So now the sync takes place entirely on the background thread created by the NSOperationQueue. This seems to work pretty well, and the UI is much more responsive during a sync.
However, I'm leery of releasing with it this way. I've seen some mentions in various places that one should only update the UI on the main thread (example with reference to AppKit). But I've been unable to find anything specific on this topic in the documentation.
So how important is it to update the UI on the main thread? Which parts of an app are thread-safe and which are not? Is there perhaps a reference explaining what's safe to execute in an NSOperation and what should be executed only on the main thread in iOS? Am I really doing something unsafe or crash-prone?
It is extremely important that you always update the UI on the main thread. Touching the UI from a background thread can cause all sorts of issues, including corruption of internal state, crashes, or just plain incorrect behavior. Any work that doesn't require touching the UI should go ahead and do on the background thread, but the bits of code that update the UI definitely needs to happen on the main thread.
The Thread Safety Summary in the Threading Programming Guide discusses which Foundation classes are thread-safe and which aren't. The whole summary is worth a skim for quick answers to common questions.
The Thread Programming Guide also has a very brief section on Threads and Your User Interface, where “it is recommended that you receive user-related events and initiate interface updates from your application’s main thread,” and “Some frameworks, such as Cocoa, generally require this behavior.” No cross-reference to a discussion of this Cocoa requirement, but I imagine I'll run across it eventually.
But the upshot is that, according to this document it is important to perform UI updates on the main thread.
Are you sure you need the NSOperation? NSXMLParser.parse and NSURLConnection.start are already asynchronous. If the class that you're parsing updates some model object, and your view controller observes that model object using KVO, you might wind up with simpler, better performing code.
There is further documentation and discussion in a technical note that goes with the ListAdder sample code. It's TN2109: 'simple and reliable threading with NSOperation'. It repeatedly talks about only updating UIKit elements from the main thread and gives examples of correct and incorrect implementations. You might find further references to it by searching 'thread confinement'.