Interviews Flashcards
(48 cards)
Await versus Tak.ContinueWith
Intrebari:
- Codul async nu blocheaza executiile viitoare, insa ce face cu liniile executate care depinde de rezultat?
————————————————-
public async void MyMainMethod()
{
await DoSomethingAsync();
//Here is a critical method that I want to execute only when
//DoSomethingAsync is finished
CriticalStuff();
}
public async Task DoSomethingAsync()
{
//Do whatever
await LongOperation();
// Rest of the method that is executed when the long operation is
//finished.
}
When DoSomethingAsync returns, it doesn’t just blindly hand control back to the calling method. It hands it a Task. If the method in fact completed synchronously, it’ll hand back a task that’s already completed. Otherwise, if the method still has work to do, the Task will be running, not (yet) completed.
So, DoSomethingAsync actually triggers some async behaviour and returns back a not-yet-completed Task to Main. What does Main do with it? It awaits it. await is how that method indicates “I can’t do anything useful unless this awaitable (usually a Task) is complete”.
Asyncronicitate, NU concurenta
If this is the first (required) await in the method, it’s at this point that the async machinery kicks in, signs up a continuation and returns from Main itself »_space;
When the local thread would be doing nothing except blocking (waiting for a reply), then : in many cases there are much better things that the thread could be doing: In the case of a client app, those “better things” include painting the UI and responding to input. In the case of a server app, those “better things” include servicing other concurrent requests / load.
——————————————————
Similarity:
So from the preceding it’s clear that both Task.ContinueWith and await Task wait for the task to finish and allows continuation after the task completion. But they work differently.
- ContinueWith
The ContinueWith function is a method available on the task that allows executing code after the task has finished execution. In simple words it allows continuation.
- await:
The await keyword causes the runtime to run the operation on a new task and causes the executing thread to return and continue with an execution. (In most cases it executes the main thread of the application). Once the await operation finishes it returns to the statement where it left off (in other words it returns to the caller, in other words it returns depending on the state saved) and starts executing statements.
Difference:
(La ContinueWith poti pierde contextul din momentul lansarii codului async)
ContinueWith doesn’t save any kind of state, the continuation operation is attached using ContinueWith run on the default thread scheduler in case a scheduler is not provided.
await: when encountering this keyword the state is saved and once the task on which await is done completes its execution the flow picks up the saved state data and starts the execution statement after await. (Note: State is having detail about executioncontext/synchronizationcontext.).
Resource: https://www.c-sharpcorner.com/UploadFile/pranayamr/difference-between-await-and-continuewith-keyword-in-C-Sharp/
Is there a new thread created for async/await?
> No, async await is just made to allow code to run whilst something else is blocking, and it doesn’t do Task. Run, or start a new thread.
The async and await keywords don’t cause additional threads to be created. Async methods don’t require multithreading because an async method doesn’t run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active.
SynchronizationContext is a representation of the current environment that our code is running in. That is, in an asynchronous program, when we delegate a unit of work to another thread, we capture the current environment and store it in an instance of SynchronizationContext and place it on Task object.
Value type vs reference type
- exemple
- diferente (alocare a memoriei, dealocare)
- poate un value type fii salvat si in alte locatii…
- sunt value type sealed?
Value:
They contain the actual values. eg (fundamental data types: -int, enum, structs).
Ref:
eg-class,interface,delegate,string,object, Array
———————————————————
Allocation
Value: Memory is allocated at compile time
Ref: Memory is allocated at run time
Value type:Value type is popped on its own from stack when they go out of scope.
Reference type:Required garbage collector to free memory.
———————————————————-
Deallocation
While the objects stored on the stack are gone when the containing stack frame is popped, memory used by objects stored on the heap needs to be freed up by the garbage collector.
When an object stored on the heap no longer has any references pointing to it, it’s considered eligible for garbage collection.
At a certain point, garbage collector kicks in, interrupts all running threads, invokes the finalizers of the objects it’s trying to get rid of (on a special finalizer thread), and then marks the memory as free to use.
Value type and it storage locations
If the value type was declared as a variable inside a method then it’s stored on the stack.
If the value type was declared as a method parameter then it’s stored on the stack.
If the value type was declared as a member of a class then it’s stored on the heap, along with its parent.
If the value type was declared as a member of a struct then it’s stored wherever that struct is stored.
Starting with C#7.2, a struct can be declared as ref struct, in which case it will always be allocated on the stack, preventing it from being declared inside reference types.
Value types- Sealed or not
Instances of value types directly contain their data. Variables that are of value types each have their own copy of the data, and therefore, an operation on one variable does not affect other variables. Value types are implicitly sealed types, since they cannot be derived from.
Boxing vs unboxing
Boxing - convertirea unui value type in reference type.
Boxing - implicit
Unboxing- explicit
– : very processive expensive
++: enables unified view of the type system wherein a value of any type can ultimately be treated as an object
Mutable vs immutable
The meaning of these words is the same in C# programming language; that means the mutable types are those whose data members can be changed after the instance is created but Immutable types are those whose data members can not be changed after the instance is created.
String context:
Why somebody should avoid to concatenate a large number of strings? What is the alternative?
• Immutable: Strings are immutable, which means we are creating new memory everytime instead of working on existing memory.
So, whenever we are modifying a value of the existing string, i.e., we are creating a new object which refers to that modified string and the old one becomes unreferenced.
• Mutable: StringBuilder is a mutable type, that means we are using the same memory location and keep on appending/modifying the stuff to one instance. It will not create any further instances hence it will not decrease the performance of the application.
Transactions- phenomena that can happen
- dirty read: read an uncommitted value, which will be might be reverted
- non repeatable reads: reading the same value in a row twice, wont fetch the same result (a nu se confumda cu dirty; e fiindca chiar s-a schimbat intre timp)
- phantom reads: All the rows in the query have the same value before and after,but different rows are being selected(because B has deleted or inserted some). Example:select sum(x) from table;will return a different result even if none of the affected rows themselves have been updated, if rows have been added or deleted.
Transaction Isolation level
- read uncommitted : dirty read can happen
- read committed , dirty read cannot happen because the transaction holds a write and read lock on the current row
- repeatable read: most restrictive isolation level- hold lock (read and write) on all isolation levels
- serializable: all transactions seem to be executed serially. No phantom read
Define ACID
Atomicity- all or nothing type if transaction
Consistency- guarantees transaction state
Isolation- assures transactions are run independently
Durability- data is never lost
Define SOLID
Single responsability principle- any class/module should have but one responsability
T: . Uncle Bob Martin (who first proposed the Single Responsibility Principle) suggests that components should be broken down until each one has only one reason to change.- not always valid as well - https://reflectoring.io/single-responsibility-principle/
Open closed principle- open to extension, close to modification. Should inherit a base instead of changing internal
Liskov substitution principle- any subtype should be able to replace its parent type, without modifying the app behaviour
Interface segregation - make small interfaces upon the need. Don’t write one that does anything
Dependency Inversion Principle- base on abstractions and not on details between the modules so you can have a loosely coupling
Explain how async/await works behind the scenes
- async is the method that marks the code that has to be executed async
- await is where the async code must complete its promise; If the code from async is not yet done, it will be returned to the its initial caller (where the await is)
- if async code is finished before reaching the await, its execution is no longer suspended and returned to the calles
- async return types:
- task: await statement (este asteptat, dar nu se returneaza nimic; folosit cu statementuri care nu returneaza nimic sau au return simplu, fara a returna un operand)
- task await: await expression (utilizat in cazul statementurilor care returneaza operands; initial se returneaza un obiect de tip task, care la “await” suspenda executia metodei in care ne aflam si populeaza si cu valoare, cand aceasta este disponibila)
- void: se folosesc rar, ca nu se pot prinde erori, de ex pentru event handlere! (eg: click pe un buton, etc)
Source: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/task-asynchronous-programming-model
Can async/await cause a deadlock?
Yes it can cause if the caller blocks the synchronization context synchronously blocks the task returned by the async code (blocking also the context thread), but the async code is waiting for the liberation of the synchronization context to finish its job.
public static async Task GetJsonAsync(Uri uri)
{
// (real-world code shouldn’t use HttpClient in a using block; this is just example code)
using (var client = new HttpClient())
{
var jsonString = await client.GetStringAsync(uri);
return JObject.Parse(jsonString);
}
}
// My “top-level” method.
public class MyController : ApiController
{
public string Get()
{
var jsonTask = GetJsonAsync(…);
return jsonTask.Result.ToString();
}
}
What is CLR?
Common Language Runtime este o masina virtuala a Microsoftului care gestioneaza rularea mai multor limbaje de programare, precum si C#. CLR ofera un managed runtime environment (nu pe OS direct), care ofera security handling, memory management, automatic garbage collection
Sursa: intrebarea 2- What is Common Language Runtime (CLR)?
Type of classes in C#?
Abstract
Sealed
Static
Partial
- to be continued
Abstract classes VS interfaces
to be continued
Abstract classes- used for objects that are closely related
Interfaces- used to define common functionality to unrelated classes
Managed VS unnmanaged code
Manged - runs on the CLR
Unnmanaged - outside the .NET framework, lacking high level language services
source: https://www.interviewbit.com/c-sharp-interview-questions/
- to be continued
Ref VS out keywords
Both are a way of passing arguments as a reference to a method. While ref is used in a bidirectional way and is used to update an existing value, out is used to retrieve multiple values (no prev instantiation, but must be initialized inside the method)
Extension methods. What are? When do we use them?
Extension methods enable you to ‘add’ methods to existing classes without creating a new derived class or modifying the existing class. They are static methods but they are called as they would be the instance’s methods.
One of the most popular extension methods are the LINQ - standard query operator methods- that add querable behavior to the IEnumerable collection.
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods
How is memory deallocated in. NET?
In the context of CLR, the garbage collection works automatically.
It is called when:
- overall memory os low
- the current generation is full
- on demand
GC works in generations, meaning that the first variables are stored on Gen0. When the first clean-up starts, what is not deleted to Gen1 and so on…
Cleaning up means that the GC will look into the app root and will delete everything that’s not global or static and is out of context.
Covariance and contravariance
Covariance is the feature that enables you to pass a derived class when a base class is expected.
Covariance: assignment is preserved
Useful in polymorphism
> Assignment compatibilit:assign a more derived object to a less derived one.
Covariance and contravariance: implicit reference conversion for arrays, delegates and generics.
Covariance preserve assignment compatibility, while contravariance reverses it.
Ex de mai sus nu vrea sa se salveze cum trebe- https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/covariance-contravariance/
Until C# 9, return type covariance won’t work.
Define DIP
Dependency inversion principle says that we should obtain decoupling by:
- high level modules should not depend on low level modules, they should be all based on abstraction
- abstraction should not depend on details, but details should depend on abstraction
Example:
1. Use abstract classes and interfaces when calling/using an object (ex: business and data layers)
2. Never use its interface directly, but apply the Inversion control principle to make the detail rely on abstraction (factory/abstract factory, strategy, template DI, service locator)
Exemplu complet era: tightly coupled > IoC (factory) > DIP (clase abstracte + înglobează factory dinainte) > DI (ctor, method, prop) > DI/IoC Container (automated DI: register, resolve, dispose)
– https://www.tutorialsteacher.com/ioc/dependency-injection
What are generics in C#?
Generic collections have added upon the simple collections, the type safety. Which means that, when initializing a generic collection, one has to specifically mention the type it’s going to be used with, leading to better performance compared to the non-generic collections, as they don’t require the hassle of boxing and un boxing.
https://www.tutorialsteacher.com/csharp/csharp-collection
Collections in C#
- Array-based
1.1. Array - continuous memory, type safe, fixed size
1.2. Arraylist- can have dynamic size but is not type safe
1.3. List-dynamic size + type safe - LinkedList - efficient for insertion and deletion, because of its structure
- Binary-tree based
3.1. Sorted Dictionary-does not have cont allocation in memory; takes more memory, but it has less hassle with the memory.
3.2. SortedList- cont memory allocation; predispose to memory fragmentation…
> both used when you frequently need the elements sorted (avoid sorting it multiple times) - What about hash maps?
https://taagung.com/c-sharp-collections-implementation/amp/
OOP Concepts
- Encapsulation - different cells express different genes. Each of them have private behaviour, they don-t have to know and access everything from its neighbour
- Abstraction-we know what some systems do, such as eating, but the majority of the process it’s a Blackbox, and we’re just using the final functionality
- Inheritance- let’s take the stem cells that differentiate into more specialized classes; they are all somehow related, and they get new behaviour as they specialize into a child class. However, the biological example wouldn’t sustain the Liskov Substitution Principle, where the child can replace the parent
- Polymorphism- the majority of animals have eyes and they behave similarly in the way they define their interface, in terms of interaction with the brain for example. However, human eye perceive 3 colors, while the mantis 12
Sorting algorithms. Their efficiency
Quick sort- in place sorting (memory efficient)