InternetException

Posts

What is SynchronizationContext in .NET

· 126 words · ~1 min read · in .NET, interview

  • multi threaded programs usually uses one of the threads as means of synchronization
  • there are message loops to pass unit of works (like Windows message queue)
  • message queues require messages formats and convention for handling it
  • single thread to handle ASP.NET request is waste of the resources (before .NET 2)
  • thread pool was better but inconvenient to work with
  • instead SynchronizationContext queues work for given context not thread
  • thread have current context
  • context does not have to be unique but can be shared between multiple threads
  • thread can change context but this is rare
  • SynchronizationContext keeps count of all asynchronous operations
  • Windows Forms uses WindowsFormsSynchronizationContext
  • WPF and Silverlight uses DispatcherSynchronizationContext
  • Console app and WindowsServices and ThreadPool threads uses default SynchronizationContext
  • ASP.NET uses AspNetSynchronizationContext

Further read:

Read the whole thing →

Does async/await creates new thread?

· 111 words · ~1 min read · in .NET, interview

#async

In short: no.

Longer explanation:

  • task that want to do I/O write call to driver write
  • driver operations are performed asynchronously
  • write operations on devices is done without CPU involved
  • finish of writing is done via interrupt
  • interrupt, schedules Deferred Procedure Call
  • DPC schedules Asynchronous Procedure Call
  • APC notifies thread that I/O write is done
  • task that was doing I/O is scheduled with continuation of its method after I/O is done.
  • some threads might need to be borrowed for handling APC and such but no thread is spawn to handle I/O

I recommend reading this post: https://blog.stephencleary.com/2013/11/there-is-no-thread.html . This will explain the topic much better than I can.

Read the whole thing →

Avoid deadlock with asynchronous methods

· 31 words · ~1 min read · in .NET, interview

#async

avoid doing AsyncOperation.Result parent method waits for Result while child method waits for parent thread to take control, after being done with async I/O both waits deadlock Further read: https://medium.com/rubrikkgroup/understanding-async-avoiding-deadlocks-e41f8f2c6f5d https://stackoverflow.com/questions/15021304/an-async-await-example-that-causes-a-deadlock

Asynchronous programming in .NET

· 46 words · ~1 min read · in .NET, interview

#async #design patterns

Asynchronous programming patterns in .NET: Asynchronous Programming Model (BeginOperation/EndOperation) Event-based Asynchronous Pattern (invoke event with result from async job) Task-based Asynchronous Pattern (Task<>) Ways of achieving asynchronous code in .NET async, await Task class API (Run, WhenAll, WhenAny, etc.) ThreadPool.QueueUserWorkItem(ThreadProc); Further read: async/await in .NET https://learn.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/

async/await in C#

· 119 words · ~1 min read · in .NET, interview

#async

async/await syntax should be used for I/O bound asynchronous operations only.

public async Task<int> GetUrlContentLengthAsync()
{
    var client = new HttpClient();

    Task<string> getStringTask =
        client.GetStringAsync("https://docs.microsoft.com/dotnet");

    DoIndependentWork();

    string contents = await getStringTask;

    return contents.Length;
}

Compiler transforms code into a state machine that to track yielding execution for await and resuming execution when a background job is finished.

Things to keep in mind:

  • async method needs await
  • add Async suffix to asynchronous methods
  • async void for ‘Fire and Forget’ work i.e. event Handlers
  • be aware of mixing LINQ with async lambdas
  • wait for tasks in a non-blocking manner (do not use Task.Result i.e.)
  • for tight loops use ValueTasks
  • Consider using ConfigureAwait(false) for performance and for avoiding deadlocks

Further read:

Read the whole thing →

CPU bound vs I/O bound

· 158 words · ~1 min read · in .NET, interview

#async

There are two types of asynchronous operations in .NET.

  • I/O bound
  • CPU bound

For I/O bound async/await syntax should be used. TPL should not be used for this. async methods does not spawns new thread to hand le I/O work asynchronously.

For CPU bound operations TPL should be used (Task.Run). This spawns new thread. Performance testing should be done to check if overhead of new thread and context switching is not greater than actual work to be done.

Read the whole thing →

SupressFinalize in IDisposable interface

· 143 words · ~1 min read · updated · in .NET, interview

  • informs GC that object does not need to be added to finalizer queue
  • finalizer execution is not deterministic and objects can live for long time in queue - this is optimization technique
  • to make sure that object disposes of any unamanaged resources even if Dispose will be not called we need to implement finalizer

Basically finalizer execution time is not deterministic. We cannot predict when this will be called and till that time - object is existing and still taking memory space. Since we are controlling creation and disposal of those resources we can say to GC: ‘Do not worry about that! It already had been taken care of!’. So this way object will be destroyed sooner, leaving this space to be used by something else possibly.

Read the whole thing →

IDisposable interface pattern

· 218 words · ~1 min read · updated · in .NET, interview

#design patterns

Example implementation of IDisposable

public class MyResource : IDisposable
{
    public MyResource(IntPtr handle)
    {
        this.handle = handle;
    }

    public void Dispose()
    {
        Dispose(disposing: true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if(!this.disposed)
        {
            if(disposing)
            {
                component.Dispose();
            }

            CloseHandle(handle);
            handle = IntPtr.Zero;
            disposed = true;
        }
    }

    ~MyResource()
    {
        Dispose(disposing: false);
    }
}

MyResource object have pointer which is unmanaged. This is why this class should implement IDisposable interface. Implementation should be correct according to recommended pattern (see below for documentation).

There a re few points to highlight here:

Read the whole thing →

General Interview Questions

· 71 words · ~1 min read · in general, interview

Closed What is asynchronous programming? What is TDD What is BDD What is DDD Open - to consider for yourself Interesting technical problem you solved lately Interesting technical problem you solved during your career What is the process of the MR/PR change review for you What is great success you accomplished lately? What skill did you improved lately? What is your greatest failure during your career? What was your biggest mistake?

What is DDD

· 67 words · ~1 min read · in general, interview

software design approach software should be driven by business domain pieces of software should match the business domain goals: domain is primary focus complex design should base on model of the domain devs and business should continuously work on refining this model to address changes in business common language for defining a business model of the domain complex logic should be abstracted to domain Further read: https://en.wikipedia.org/wiki/Domain-driven_design

What is BDD

· 66 words · ~1 min read · in general, interview

based on TDD better collaboration between devs, QAs and business than TDD behavioral tests first, implementation second behavioral tests should be easy to understand, simple those tests should be written in specific language, possible to understood by business combines idea of unit tests naming, acceptance tests standard agile framework (As a XXX I want YY to achieve ZZ), and acceptance criteria with Gherkin Further read: https://en.wikipedia.org/wiki/Behavior-driven_development

What is TDD

· 32 words · ~1 min read · in general, interview

Test-driven development software requirements are converted to tests cases *before* actual implementation implementation is done against all those test cases opposing to first writing an implementation then tests cases Further read: https://en.wikipedia.org/wiki/Test-driven_development

What is asynchronous programming?

· 589 words · ~2 min read · updated · in general, interview

#async

  • software often waits for some I/O operation to complete (file operation, network call, database query etc.)
  • we can use this time for something productive instead to wait for data to be available or I/O operation to be completed
  • with asynchronous programming user can work in the meantime
  • not waiting for I/O operations synchronously enhances user experience

Of course this problem is much more complex. Modern software operates on much more different PC architecture than 20 years ago. Nowadays software must be asynchronous to appear more user friendly and to made better use of modern multi CPU architecture. Right now complex, professional software uses multiple processes, threads on multiple CPUs (CPU you buy is not really *single* CPU) or even utilize GPU for more complex computations (like i.e. video editing software). Before that we mostly had single threaded desktop applications that had ‘please wait’ or ’loading’ pop ups. Right now this is song of the past really and to achieve better User Interfaces that allow to edit tag of your post without changing whole post. With mobile devices on the rise and sometimes lousy cellular network those kind of designs would not be sensible or sometimes impossible to implement. Did you ever happened to reenter some chunk of data into some software because you lost it? Maybe network was down? Or you hit back button by mistake? Right now it belongs to past mostly. All of those would be hard to do with synchronous operations. Right now people are bit spoiled and they tend to leave the page/application if it appears to be slow and not every company can sell ‘one-in-the-market-necessary-for-your-work-software’ that you will be forced to use. And this is why we have asynchronous operations and this is why we have asynchronous programming model that allows us to program such operations.

Read the whole thing →

Automatic scrolling to edited text box in Xamarin Android.

· 858 words · ~4 min read · updated · in .NET, Android, C#, Xamarin

Important note: this should work well with newer version of Xamarin (2.3.3). If you cannot update for some reason this article will explain workaround.

Introduction

In previous article I explained how to detect show and hide events of software keyboard in Xamarin Android. I did it in my project because of the fact that some of text boxes was hidden by software keyboard that suppose to edit contents of those text boxes. In this article I will explain how to work around this issue in some older versions of Xamarin.

Read the whole thing →