Does the SynchronizationContext is used only for WPF,Win forms? - c#

Each article i read about SynchronizationContext talks on dealing with the form's controls.
Is it the only purpose of the SynchronizationContext?
And I have to ask a basic thing also: Why cant I just do a lock on each control befor i use if the UI thread use it? why i need all this "SynchronizationContext" to communicate with the controls? I mean, isnt it a better way to communicate the controls? (I know it wont work).
Articles:
http://blogs.msdn.com/b/csharpfaq/archive/2010/06/18/parallel-programming-task-schedulers-and-synchronization-context.aspx
http://reedcopsey.com/2010/03/18/parallelism-in-net-part-15-making-tasks-run-the-taskscheduler/
..

SynchronizationContext can be used to execute work in any other thread's context.
There is a main caveat here though: the other thread needs to be prepared for that, e. g. by using a message pump, like the UI threads in WinForm and WPF do. Also, those UI threads always have a SynchronizationContext, while other thread types typically don't.
As for locking as an alternative, that would need a completely different design inside Microsoft classes. It might be possible, though it might also result in threads blocking for a long time when waiting. I think it would open a lot of possibilities for misuse.
This article on codeproject is rather helpful, like https://stackoverflow.com/a/4107653/586754.

Related

Why is "InvokeOnAppThread" used?

(The question is following but please read the info below as well)
According to the documentation InvokeOnAppThread executes a callback item on application thread.
Browsing more into the documentation , it seems there is the "UI Thread" and the "application thread".
However the link they offered for more information on this, is not there.
So, is there by default two threads on any Unity program? Can someone explain to me about InvokeOnAppThread? Why and when it should be used?
(I have already searched and looked on pages dealing with threading in Unity. It is clear there is a UI Thread by default and it seems multithreading is not recommended since other threads are not allowed access to the UI Thread. As I understand this can be solved by using callbacks)- so I have already done research on this
The "Application thread" mentioned in the docs is not mentioned anywhere else
Just to avoid duplicates I have already searched in SO if there is already an answer to this. The search output 0 results, so it is clear to the best of my efforts this is not a duplicate question
It looks like this is the page that should be reached from the broken link.
From that page:
Now, let’s take a closer look at AppCallbacks class. When you create
it, you specify that your game will run on different thread, for
backward compatibility reasons you can also specify that your
application can run on UI thread, but that’s not recommended, because
there’s a restriction from Microsoft - if your application won’t
become responsive after 5 seconds you’ll fail to pass WACK (Windows
Application Certification), read more here -
http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh184840(v=vs.105).aspx,
imagine if your first level is pretty big, it might take significant
amount of time to load it, because your application is running on UI
thread, UI will be unresponsive until your level is fully loaded.
That’s why it’s recommend to always run your game on different thread.
Essentially the 'UI thread' is the main thread from the point of view of the WinRT/UWP runtime. In order not to block that thread, all Unity-specific code - MonoBehaviour scripts, coroutines, etc - runs on a separate thread, the 'application thread,' which is the main thread from the point of view of the Unity engine.
You would use InvokeOnUIThread if you were on Unity's main thread and you wanted to do something on the Windows UI thread (eg, create a native pop-up). You'd call InvokeOnAppThread if you were on the UI thread and wanted to marshal back to the Unity main thread (eg, start a coroutine, instantiate a GameObject).
I'm not familiar with Unity, but this is a typical requirement with WinForms development in whatever framework you are using.
You can find detailed description of the issue in the Control.InvokeRequired property documentation and also in this MSDN page.
What the explanations say is that events for a control should only be handled by the thread that created them because otherwise they are not thread safe. This is a little different than the guidance I have understood in the past - your main UI thread is just listening for events and handing them off to a ThreadPool for processing so that user responsiveness (ie. responding to mouse/keyboard events) never halts because the app is doing something.
The Control.InvokeRequired check is supposed to tell you if you are on the UI thread so that you can queue another event that should execute on a different thread so the main UI handling thread does not block. The implementation details may have changed somewhat since I last worked with this, though.

C#.NET: "Multi Threaded Apartment" and "Multithreading"

I am learning multi threading concepts (in general and targeted to C#.NET). Reading different articles, still could not fully understand few basic concepts.
I post this question. "Hans Passant" explained it well but I was not able to understand some of its part. So I started googling.
I read this question which have no answers.
Is Multithreading and MTA same?
Suppose I write a WinForm application which is STA (as mentioned above its Main() method), still I can create multiple threads in my application. I can safely say my application is "multi-threaded". Does that also mean my application is MTA?
While talking about STA/MTA, most of the articles (like this) talk about COM/DCOM/Automation/ActiveX. Does that mean DotNet have nothing to do with STA/MTA?
No. MTA is a property of a single thread, just like STA. You now make the exact opposite promise, you declare that the thread does absolutely nothing to keep external code thread-safe. So no need to have a dispatcher and you can block as much and as long as you like.
This has consequences of course and they can be quite unpleasant. It is deadly if the UI thread of your program is in the MTA since it uses so many external components that are fundamentally thread-unsafe. The clipboard won't work, drag+drop doesn't work, OpenFileDialog typically just hangs your program, WebBrowser won't fire its events.
Some components check for this and raise an exception but this check isn't consistently implemented. WPF is notable, while apartment state normally matters only to unmanaged code, WPF borrowed the concept and raises "The calling thread must be STA, because many UI components require this." Which is a bit misleading, what it really means is that the thread must have a dispatcher to allow its controls to work. But otherwise consistent with the STA promise.
It can work when the component uses COM and the author has provided a proxy. The COM infrastructure now steps in to make the component thread-safe, it creates a new thread that is STA to give it a safe home. And every method call is automatically marshaled so it runs on that thread, thus providing thread-safety. The exact equivalent of Dispatcher.Invoke() but done entirely automatic. The consequence however is that this is slow, a simple property access that normally takes a few nanoseconds can now take multiple microseconds.
You'd be lucky if the component supports MTA as well as STA. This is not common, only somebody like Microsoft goes the extra thousand miles to keep their libraries thread-safe.
I should perhaps emphasize that the concepts of apartments is entirely missing in the .NET Framework. Other than the basics of stating the apartment type, necessary since .NET programs often need to interop with unmanaged code. So writing a Winforms app with worker threads is just fine, and those worker threads are always in the MTA, you do however get to deal with thread-safety yourself and nothing is automatic.
This is generally well-understood, just about everybody knows how to use the lock keyword, the Task and BackgroundWorker classes and knows that the Control.Begin/Invoke() method is required to update UI from a worker thread. With an InvalidOperationException to remind you when you get it wrong. Leaving it up to the programmer instead of the system taking care of thread-safety does make it harder to use threads. But gives you lots of opportunities to do it better than the system can. Which was necessary, this system-provided thread-safety got a serious black eye when Java punched it in the face during the middleware wars of the late 90s.
There are some questions but first let's start by this:
An Apartment is a context where a COM object is initialized and executed, and it can be a either single thread (STA), normally used for not thread-safe objects, or multi thread.
the term apartment, which describes the constructs in which COM
objects are created
From: https://msdn.microsoft.com/en-us/library/ms809971.aspx
So Multithreading and MTA are not the same, but MTA is Multithreaded.
We can say that STA and MTA are related to COM objects.
You can read more here: https://msdn.microsoft.com/en-us/library/ms693344(v=vs.85).aspx
So, for your second question, if your WinForm application is "multi-threaded" does not mean it is "MTA".
Finally, the MTA/STA concepts are older than .Net technology, but we cannot say that they have nothing related to, because .Net supports COM technology in both STA and MTA.
I expect my answer help you to undestand the difference between Apartment and Threading.
More interesting reading here:Could you explain STA and MTA?

Should I use Invoke or SynchronizationContext to update form controls from another thread?

Trying to wrap my head around updating UI controls from other threads.
Currently using BeginInvoke and honestly it's working fine but I keep hearing about how you can use SynchronizationContext as well to do the same thing.
Which is preferred?
Also, is it bad practice to update the UI from a thread? Would it be better to raise an event and have the main form handle it instead or are there other preferable ways to do that as well?
Sorry for the somewhat subjective question but there are so many options in the world of threading and I'm trying to grasp their differences and where each of them are applicable, along with best practices for writing readable and extendable code for the future.
Edit: Also now I see there is the TaskScheduler.FromCurrentSynchronizationContext route as well.. So many choices x_x
I prefer SynchronizationContext over Control.Invoke. The danger of Control.Invoke is that there is a lifetime issue with the owning Control. If the Control is disposed while you are trying to Invoke on it then it compromises the ability of the call to succeed. This happens when dialogs are closed, views shifted, etc ...
SynchronizationContext.Current though generally lives as long as the thread it's associated with. It does have a finite lifetime and hence ultimately the same problems but it's a bit more predictable than a Control.
Have you looked into using a Background Worker component? For long running tasks that shouldn't tie up the UI it is a clean and easy way to get multithreading capabilites. For instance you can perform updates to the UI using the ProgressChanged Event and the background worker and the background worker class will ensure that the thread that created the BW is the one that executes the ProcessChanged and WorkComplete event. So if you made the BW from the UI and set it off to work then you can update the UI safely from there.
Here's a quick article from MS
http://msdn.microsoft.com/en-us/library/cc221403%28v=vs.95%29.aspx
Another really good link
http://www.albahari.com/threading/part3.aspx#_BackgroundWorker

Which async call use for DB connection and still responsive GUI?--

My application connects to MySQL but sometimes it takes a while and the GUI is getting frozen. I would like to do the connection on the other thread, I guess BeginInvoke would be the best way (I know about background worker but I would like to learn this). I have studied MSDN page but I did not understand what is the best way to use?
They also say that you can use only callback when the thread that called the async.method does not need to know the results...I dont understand it as I believe I can set some variable in the other thread to "pass" the result well.
I would just need the GUI to be not frozen while the connection is being established. Thank you for your advice.
By far the easiest way to handle it is to use a BackgoundWorker. It is specifically designed to take care of most threading issues such as marshalling progress events and completion notices from the background thread to the GUI thread. I've used it to great success with both WinForms and WPF.
I know many other methods for doing this, but they all take two or three attempts for me to get right.

Multithreading: how to update UI to indicate progress

I've been working on the same project now since Christmas 2008. I've been asked to take it from a Console Application (which just prints out trace statements), to a full Windows App. Sure, that's fine. The only thing is there are parts of the App that can take several minutes to almost an hour to run. I need to multithread it to show the user status, or errors. But I have no idea where to begin.
I've aready built a little UI in WPF. It's very basic, but I'd like to expand it as I need to. The app works by selecting a source, choosing a destination, and clicking start. I would like a listbox to update as the process goes along. Much in the same way SQL Server Installs, each step has a green check mark by its name as it completes.
How does a newbie start multithreading? What libraries should I check out? Any advice would be greatly appreciated.
p.s. I'm currently reading about this library, http://www.codeplex.com/smartthreadpool
#Martin: Here is how my app is constructed:
Engine: Runs all major components in pre-defined order
Excel: Library I wrote to wrap COM to open/read/close/save Workbooks
Library: Library which understands different types of workbook formats (5 total)
Business Classes: Classes I've written to translate Excel data and prep it for Access
Db Library: A Library I've written which uses ADO.NET to read in Access data
AppSettings: you get the idea
Serialier: Save data in-case of app crash
I use everything from LINQ to ADO.NET to get data, transform it, and then output it.
My main requirement is that I want to update my UI to indicate progress
#Frank: What happens if something in the Background Worker throws an Exception (handled or otherwise)? How does my application recieve notice?
#Eric Lippert: Yes, I'm investigating that right now. Before I complicate things.
Let me know if you need more info. Currently I've running this application from a Unit Test, so I guess callig it a Console Application isn't true. I use Resharper to do this. I'm the only person right now who uses the app, but I'd like a more attractive interface
I don't think you specify the version of the CLR you are using, but you might check out the "BackgroundWorker" control. It is a simple way to implemented multiple threads.
The best part, is that it is a part of the CLR 2.0 and up
Update in response to your update: If you want to be able to update the progress in the UI -- for example in a progress bar -- the background worker is perfect. It uses an event that I think is called: ProgressChanged to report the status. It is very elegant. Also, keep in mind that you can have as many instances that you need and can execute all the instances at the same time (if needed).
In response to your question: You could easily setup an example project and test for your question. I did find the following, here (under remarks, 2nd paragraph from the caution):
If the operation raises an exception
that your code does not handle, the
BackgroundWorker catches the exception
and passes it into the
RunWorkerCompleted event handler,
where it is exposed as the Error
property of
System.ComponentModel..::.RunWorkerCompletedEventArgs.
Threading in C# from Joseph Albahari is quite good.
This page is quite a good summary of threading.
By the sound of it you probably don't need anything very complex - if you just start the task and then want to know when it has finished, you only need a few lines of code to create a new thread and get it to run your task. Then your UI thread can bumble along and check periodically if the task has completed.
Concurrent Programming on Windows is THE best book in the existence on the subject. Written by Joe Duffy, famous Microsoft Guru of multithreading. Everything you ever need to know and more, from the way Windows thread scheduler works to .NET Parallels Extensions Library.
Remember to create your delegates to update the UI so you don't get cross-threading issues and the UI doesn't appear to freeze/lockup
Also if you need a lot of notes/power points/etc etc
Might I suggest all the lecture notes from my undergrad
http://ist.psu.edu/courses/SP04/ist411/lectures.html
The best way for a total newcomer to threading is probably the threadpool. We'll probably need to know a little more about these parts to make more in depth recommendations
EDIT::
Since we now have a little more info, I'm going to stick with my previous answer, it looks like you have a loads of tasks which need doing, the best way to do a load of tasks is to add them to the threadpool and then just keep checking if they're done, if tasks need to be done in a specific order then you can simply add the next one as the previous one finishes. The threadpool really is rather good for this kind of thing and I see no reason not to use it in this case
Jason's link is a good article. Things you need to be aware of are that the UI can only be updated by the main UI thread, you will get cross threading exceptions if you try to do it in the worker thread. The BackgroundWorker control can help you there with the events, but you should also know about Control.Invoke (or Control.Begin/EndInvoke). This can be used to execute delegates in the context of the UI thread.
Also you should read up on the gotchas of accessing the same code/variables from different threads, some of these issues can lead to bugs that are intermittent and tricky to track down.
One point to note is that the volatile keyword only guarantees 'freshness' of variable access, for example, it guarantees that each read and write of the variable will be from main memory, and not from a thread or processor cache or other 'feature' of the memory model. It doesnt stop issues like a thread being interrupted by another thread during its read-update-write process (e.g. changing the variables value). This causes errors where the 2 threads have different (or the same) values for the variable, and can lead to things like values being lost, 2 threads having the same value for the variable when they should have different values, etc. You should use a lock/monitor (or other thread sync method, wait handles, interlockedincrement/decrement etc) to prevent these types of problems, which guarantee only one thread can access the variable. (Monitor also has the advantage that it implicitly performs volatile read/write)
And as someone else has noted, you also should try to avoid blocking your UI thread whilst waiting for background threads to complete, otherwise your UI will become unresponsive. You can do this by having your worker threads raise events that your UI subscribes to that indicate progress or completion.
Matt
Typemock have a new tool called Racer for helping with Multithreading issues. It’s a bit advanced but you can get help on their forum and in other online forums (one that strangely comes to mind is stackoverflow :-) )
I'm a newbie to multithreading as well, but I agree with Frank that a background worker is probably your best options. It works through event subscriptions. Here's the basics of how you used it.
First Instantiate a new background worker
Subscribed methods in your code to the background workers major events:
DoWork: This should contain whatever code that takes a long time to process
ProgressChanged: This is envoked whenever you call ReportProgress() from inside the method subscribed to DoWork
RunWorkerCompleted: Envoked when the DoWork method has completed
When you are ready to run your time consuming process you call the RunAsync() method of the background worker. This starts DoWork method on a separate thread, which can then report it's progress back through the ProgressChanged event. Once it completed RunWorkerComplete will be evoked.
The DoWork event method can also check if the user somehow requested that the process be canceled (CanceLAsync() was called)) by checking the value of the CancelPending property.

Categories

Resources