Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, 20 May 2020

Generator Functions in various Programming Languages

A generator is a special type of function which can pause its execution, yield result back to the caller and resume later, at caller’s convenience. And this happens as long as the generator has something to return, some value to yield back. Caller is usually iterating over yielded values in a loop, it takes a new value as soon as generator yields it. The main benefit of generators is that not all elements in a  sequence have to be kept in memory at the same time but only a single one. 



Generators in Python


Wednesday, 26 April 2017

How to add a NuGet package to C# project in VSCode on Ubuntu

In VSCode open Terminal and use dotnet CLI command package and specify the name of the desired package (e.g. Newtonsoft.Json):


$ dotnet add package Newtonsoft.Json



This will add a reference to that NuGet package in project:



Output in VSCode:


This can be verified in the project file:



VSCode notifies us that there are unresolved dependencies:


If we click on Restore newtonsoft.json library gets downloaded to ~/.nuget/packages directory.

After resolving them we can start using object from the newly added package. Intellisense also works for new dependency assembly:


Saturday, 22 April 2017

How to run .NET Core console application in VSCode on Ubuntu


In the previous article I demonstrated how to create simple .NET Core "Hello, world!" console application and here I want to show how can we load, run and debug that project in VSCode.

In VSCode, open TestProject directory. All generated files are shown in the left pane. VSCode downloads and installs required packages:




Required assets are standard VSCode JSON files so after we answer Yes to the first question .vscode directory appears:


Clicking on Restore triggers restoring packages:


If we hit F5, VSCode will execute the program:


We can set the breakpoints as well:


How to create .NET Core Console application on Ubuntu


To create .NET project of desired type we can use .NET Core command line tool (dotnet). Let's see the list of all possible project types:

$ dotnet new

Template Instantiation Commands for .NET Core CLI.

Usage: dotnet new [arguments] [options]

Arguments:
template The template to instantiate.

Options:
-l|--list List templates containing the specified name.
-lang|--language Specifies the language of the template to create
-n|--name The name for the output being created. If no name is specified, the name of the current directory is used.
-o|--output Location to place the generated output.
-h|--help Displays help for this command.
-all|--show-all Shows all templates


Templates Short Name Language Tags
----------------------------------------------------------------------
Console Application console [C#], F# Common/Console
Class library classlib [C#], F# Common/Library
Unit Test Project mstest [C#], F# Test/MSTest
xUnit Test Project xunit [C#], F# Test/xUnit
ASP.NET Core Empty web [C#] Web/Empty
ASP.NET Core Web App mvc [C#], F# Web/MVC
ASP.NET Core Web API webapi [C#] Web/WebAPI
Solution File sln Solution

Examples:
dotnet new mvc --auth None --framework netcoreapp1.1
dotnet new classlib
dotnet new --help

To create Console application project we have to use console:
$ dotnet new console -o TestProject -n HelloWorld
Content generation time: 54.4945 ms
The template "Console Application" created successfully.

This creates a directory TestProject and in it project named HelloWorld and intial source code file:
$ ls
TestProject

$ cd TestProject/

/TestProject$ ls
HelloWorld.csproj Program.cs

HelloWorld.csproj:
/TestProject$ cat HelloWorld.csproj


Program.cs:
/TestProject$ cat Program.cs


Let's now update dependencies (NuGet packages) and tools specified in the project:
/TestProject$ dotnet restore
Restoring packages for /home/bojan/Downloads/test/TestProject/HelloWorld.csproj...
Generating MSBuild file /home/bojan/Downloads/test/TestProject/obj/HelloWorld.csproj.nuget.g.props.
Generating MSBuild file /home/bojan/Downloads/test/TestProject/obj/HelloWorld.csproj.nuget.g.targets.
Writing lock file to disk. Path: /home/bojan/Downloads/test/TestProject/obj/project.assets.json
Restore completed in 492.24 ms for /home/bojan/Downloads/test/TestProject/HelloWorld.csproj.

NuGet Config files used:
/home/bojan/.nuget/NuGet/NuGet.Config

Feeds used:
https://api.nuget.org/v3/index.json

This creates obj directory and various config files:
/TestProject$ ls
HelloWorld.csproj obj Program.cs

/TestProject$ cd obj/

/TestProject/obj$ ls
HelloWorld.csproj.nuget.g.props HelloWorld.csproj.nuget.g.targets project.assets.json

HelloWorld.csproj.nuget.g.props:
/TestProject/obj$ cat HelloWorld.csproj.nuget.g.props


HelloWorld.csproj.nuget.g.targets:
/TestProject/obj$ cat HelloWorld.csproj.nuget.g.targets


project.assets.json:
/TestProject/obj$ cat project.assets.json


We can now build the project and run the binary output:
/TestProject$ dotnet run
Hello World!

This command built the project and placed binary output and other build artifacts in newly created bin directory:
/TestProject$ ls
bin HelloWorld.csproj obj Program.cs

/TestProject$ cd bin

/TestProject/bin$ ls
Debug

/TestProject/bin$ cd Debug/

/TestProject/bin/Debug$ ls
netcoreapp1.1

/TestProject/bin/Debug$ cd netcoreapp1.1/

/TestProject/bin/Debug/netcoreapp1.1$ ls
HelloWorld.deps.json HelloWorld.dll HelloWorld.pdb HelloWorld.runtimeconfig.dev.json HelloWorld.runtimeconfig.json

.deps.json (dependencies JSON file) lists dependencies of the application:
/TestProject/bin/Debug/netcoreapp1.1$ cat HelloWorld.deps.json


.runtimeconfig.dev.json:
/TestProject/bin/Debug/netcoreapp1.1$ cat HelloWorld.runtimeconfig.dev.json


.runtimeconfig.json file specifies the shared runtime and its version for the application:
/TestProject/bin/Debug/netcoreapp1.1$cat HelloWorld.runtimeconfig.json


It might seem unexpected that the binary output is not .exe but .dll. This is because default .NET Core's deployment model is Framework-dependent deployment, where output assembly contains only compiled source and 3rd party dependencies but not .NET Core dependencies - assembly assumes that .NET Core Framework and runtime are installed on the target machine. This is why we have to use dotnet tool to run it:

/TestProject/bin/Debug/netcoreapp1.1$ dotnet HelloWorld.dll
Hello World!

The other type of deployment is Self-contained deployment in which case the output assembly is .exe and contains .NET Core dependencies and runtime - nothing else is necessary to be installed on the target system.


References:

.NET Core application deployment
.NET Core command-line interface (CLI) tools

Tuesday, 23 August 2016

Why is async void bad?

Methods returning void are not awaitable. await operator can be applied only to methods which are returning Task or Task

Let's assume that method Bar is async void. Consequences of  having method Foo calling method Bar are the following:

  • This is a fire and forget model: Foo can't get information when Bar terminates as it can't await on async void method. Foo continues to run before Bar call is completed.
  • If Bar throws an exception, Foo can't catch it as there is no Task object to carry the exception object.
For these reasons async void methods shall be avoided. But this rule has a single exception; top-level events (e.g. GUI events) of void type can be async,

Links:


https://channel9.msdn.com/Series/Three-Essential-Tips-for-Async/Tip-1-Async-void-is-for-top-level-event-handlers-only

http://blog.stephencleary.com/2014/02/synchronous-and-asynchronous-delegate.html


http://stackoverflow.com/questions/15522900/how-to-safely-call-an-async-method-in-c-sharp-without-await

http://stackoverflow.com/questions/23285753/how-to-await-on-async-delegate

http://stackoverflow.com/questions/20624667/how-do-you-implement-an-async-action-delegate-method

Friday, 8 July 2016

Logic in getters and setters

Setters:
  • used to set a (new) value of a property
  • expected to be fast
  • value can be validated (e.g. null check, range check etc...); failed validation CAN throw exception
  • event which publishes information that property's value has been changed can be fired; event handlers are not under publisher's control and they CAN throw exception


Getters:
  • return value of the property
  • expected to be fast
  • expected to be idempotent (i.e. no destructive actions should be performed there)
  • expected to cause no side effects on the object (no changing values)
  • MUST NOT throw exception (otherwise would break principle of least surprise)
  • use memoisation (lazy computation/evaluation)



References:
Property Design (MSDN)
http://stackoverflow.com/questions/495864/logic-in-get-part-of-property-good-practice
http://stackoverflow.com/questions/2923116/is-it-a-good-practice-to-implement-logic-in-properties
http://stackoverflow.com/questions/1488472/best-practices-throwing-exceptions-from-properties

Friday, 1 January 2016

How to use internal type as a unit test argument

Behavioral tests sometimes require access to types which are internal for the SUT assembly. If those types are used in test methods, test assembly name has to be specified through InternalsVisibleToAttribute in SUT assembly. For example, if MyAppTests is a library containing tests for classes within MyApp we have to do the following:
  • in MyAppTests: add the reference to MyApp so all public types are visible
  • in MyApp: specify MyAppTests as the assembly in which internal types are visible. The following line has to be added to MyApp/Properties/AssemblyInfo.cs:

[assembly: InternalsVisibleTo("MyAppTests")]



This makes internal types visible within unit tests. But if we want to pass such types as arguments to unit tests (via TestCase or TestCaseSource attributes), compiler will complain about inconsistent accessibility.

For example, if we have public class (SUT) and internal enum:


and the following test:


Compiler issues an error:

Error CS0051 Inconsistent accessibility: parameter type 'MyEnum' is less accessible than method 'MyClass_Tests.Foo_Does_This_When_MyEnum_Is_Value1_or_Value2(MyEnum)'

Unit test methods have to be public, otherwise unit test runners will not be able to see them or would report that test fails (Nunit Test Adapter also issues error message: "Method is not public"). Unit tests are public API so types of their arguments also have to be public (visible in any assembly, not just in test library).

The solution for this is to pass arguments to test method as type object and then cast them back to the original internal type:


In this particular case, when internal type is enum, we could gave passed type int instead of object but for any other custom internal type, object is the only solution.


Thread which explains reasons why NUnit fails but does not ignore non-public test methods.

Thursday, 24 December 2015

DRY in action - Use lambda to fixate method's argument


In the following example we have a situation where Foo() calls Bar() multiple times. Within each Foo() call, it passes to Bar() different value for string argument but always the same value for int argument:

Output:


i = 123, s = test1
i = 123, s = test2
i = 123, s = test3
i = 456, s = test1
i = 456, s = test2
i = 456, s = test3


To avoid unnecessary repetition we can introduce one level of indirection - a lambda which calls Bar() and provides it string value via its own argument and int value via capturing argument passed to Foo(). After refactoring:

Output:


i = 123, s = test1
i = 123, s = test2
i = 123, s = test3
i = 456, s = test1
i = 456, s = test2
i = 456, s = test3


Monday, 21 December 2015

OperationCanceledException vs TaskCanceledException when task is canceled


In my previous post, "How to cancel a Task", I mentioned that MSDN recommends throwing OperationCanceledException from a cancelled task. But the following example shows that canceling .NET methods makes them throw a different exception type - TaskCanceledException:

Output:


System.Threading.Tasks.TaskCanceledException: A task was canceled.
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Program.d__1.MoveNext()
Task.IsCanceled: True
Task.IsFaulted: False
Task.Exception: null


So why .NET does not follow its own rules? Why exception thrown in the example above was not OperationCanceledException?

I asked this question on SO and this is how I interpret the answer I got:

(1) System.OperationCanceledException class has been around longer than TPL. MSDN describes it as: "The exception that is thrown in a thread upon cancellation of an operation that the thread was executing." It is intended to be thrown from a thread in which operation is executed. .NET async API are actually synchronous operations (return Task, not marked as async). They don't have additional thread involved which makes OperationCanceledException not appropriate exception to be thrown.

(2) It is different to cancel a Task (setup of the engine which will execute "real work", user's operation) than to cancel operation itself. For example, we can pass already cancelled token to a task or can simply create already cancelled task. Operation and its thread are not started at all in these cases but if we await such task and catch OperationCanceledException we might think they were actually started. So it makes sense to use different type of the exception in these two different scenarios.

Example 1: Already canceled token is passed to task factory method:

Output:


System.Threading.Tasks.TaskCanceledException: A task was canceled.
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Program.d__1.MoveNext()
Task.IsCanceled: True
Task.IsFaulted: False
Task.Exception: null


Example 2: Awaiting task which is created as already canceled:

Output:


System.Threading.Tasks.TaskCanceledException: A task was canceled.
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNot
ification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Program.d__1.MoveNext()
Task.IsCanceled: True
Task.IsFaulted: False
Task.Exception: null


From the points made above we can conclude that caller of the cancelable task can expect two types of exceptions:OperationCanceledException and TaskCanceledException. As the latter derives from the former, it is enough to handle OperationCanceledException if we want to handle the case of canceled task:




Further reading:
SO Q&A: OperationCanceledException VS TaskCanceledException when task is canceled
SO Q&A: Difference between OperationCanceledException and TaskCanceledException?
Andrew L Arnott: Recommended patterns for CancellationToken

Sunday, 20 December 2015

How to cancel a Task


It is a good practice to offer users a chance to cancel some long-running operation. Such operation usually has to run asynchronously and in a TPL-based design is modeled as a method returning a Task.

Cancellation model requires some flag which is accessible by the caller and from inside the operation. Caller sets the flag when wants operation to be cancelled. Operation regularly checks the flag or is subscribed to the event "flag has been set" and if flag has been set, operation will stop doing the work. This model is in .NET abstracted with two types: CancellationTokenSource class and CancellationToken structure. Caller uses CancellationTokenSource to initiate cancellation and operation uses CancellationToken to check whether it has been cancelled.

When designing an API, if provision for operation cancellation is required, we have to add a CancellationToken to a list of method's arguments. API caller invokes CancellationTokenSource.Cancel method which sets CancellationToken.IsCancellationRequested to true. Target method checks this property and can either silently return or throw OperationCanceledException. The latter approach is better as only in this case returning task will come to Canceled state.

The following code depicts the whole process of task cancellation:

CancellationToken.ThrowIfCancellationRequested() method simply checks CancellationToken.IsCancellationRequested and if it's true, it throws OperationCanceledException. The output of the code above is:


.........System.OperationCanceledException: The operation was canceled.
   at System.Threading.CancellationToken.ThrowIfCancellationRequested()
   at MyService.d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Program.d__1.MoveNext()
Task.IsCanceled: True
Task.IsFaulted: False
Task.Exception: null


The following code shows that the await-ed task does not get aware that the task it holds got canceled if method silently returns on cancellation:

Output:

..........Task.IsCanceled: False
Task.IsFaulted: False
Task.Exception: null


Further reading:
Andrew Arnott - Recommended patterns for CancellationToken
MSDN: Task Cancellation

Saturday, 19 December 2015

await VS Wait() when Task throws exception

await and Wait() are two versions of the operation "wait for the task to complete": one is asynchronous (non-blocking) and the other one is synchronous (blocking). They are both capable of capturing the exception thrown from the task but they behave in a different way when propagating exception information up the stack: they themselves throw different type of exception.


await (case 1) propagates the original exception so the output is:


System.ArgumentNullException: Value cannot be null.
   at Program.<>c.b__1_0()
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Program.d__1.MoveNext()
Task.Status: Faulted
Task.IsFaulted: True
Task.Exception: System.AggregateException: One or more errors occurred. ---> System.ArgumentNullException: Value cannot be null.
   at Program.<>c.b__1_0()
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Program.d__1.MoveNext()
   --- End of inner exception stack trace ---
---> (Inner Exception #0) System.ArgumentNullException: Value cannot be null.
   at Program.<>c.b__1_0()
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Program.d__1.MoveNext()<---


Wait() (case 2) wraps original exception in System.AggregateException:


System.AggregateException: One or more errors occurred. ---> System.ArgumentNullException: Value cannot be null.
   at Program.<>c.b__1_0()
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at System.Threading.Tasks.Task.Wait()
   at Program.d__1.MoveNext()
---> (Inner Exception #0) System.ArgumentNullException: Value cannot be null.
   at Program.<>c.b__1_0()
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()<---

Task.Status: Faulted
Task.IsFaulted: True
Task.Exception: System.AggregateException: One or more errors occurred. ---> System.ArgumentNullException: Value cannot be null.
   at Program.<>c.b__1_0()
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
   --- End of inner exception stack trace ---
---> (Inner Exception #0) System.ArgumentNullException: Value cannot be null.
   at Program.<>c.b__1_0()
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()<---


Note that Task.Exception in both cases holds System.AggregateException. This difference comes from the desire of async-await implementers to keep use of await as simple as possible and to make its use to look like synchronous code as much as possible. System.AggregateException is not used in synchronous code (in non-TPL code) and we there always catch the first exception that is thrown from a try-block. That is why await is designed in such way so it throws only the first exception from a task (or aggregate of tasks) as usually we are interested only in that first exception (we usually handle the first error that occurs).

Null-Conditional Operator in C# 6


C# 6 introduced a Null-Conditional operator which makes null checks more concise. If object on which it is applied is null, it will immediately return null, if not, it will return result of the operation applied on that object (invoking method, property...onto which other operations might be chained). Instead of writing:


var personName = person == null ? null : person.Name;


...we can write:


var personName = person?.Name;


?. is a first form of this operator. The other one is ?[] and is used when accessing array elements. Instead of performing null check of the array and then accessing its elements, we can now put those two operations in a single expression:


var arr = new string[]{"abc" , "def"};
var arr0 = arr?[0]; // "abc"
arr = null;
arr0 = arr?[0]; // null


This operator comes very handy when raising events. Before, we would write:


public event Action SomeEvent;
private void OnSomeEvent()
{
   if (SomeEvent != null)
   {
      SomeEvent.Invoke();
   }
}


...but now we can write:


public event Action SomeEvent;
private void OnSomeEvent()
{
   SomeEvent?.Invoke();
}


Friday, 18 December 2015

String interpolation in C# 6

With C# 6 we can finally wave goodbye to the cumbersome, C-style way of injecting values into a string. Before, target string and arguments were separated and indexes were used to place the right argument at the right place inside the string. That was an error prone process.


var id = 123;
var name = "abc";
var s = string.Format("id = {0}, name = {1}", id, name);


New interpolation syntax allows direct injection of variables into the string:


var id = 123;
var name = "abc";
var s = $"id = {id}, name = {name}";


It is possible to inject string result of some more complex expressions:


var task = new Task();
var taskExceptionReport = 
   $"Task.Exception: {((task.Exception == null) ? "null" : task.Exception.ToString())}";



Further reading:
Interpolated Strings (MSDN)
Bill Wagner: "A Pleasant New C# Syntax for String Interpolation"

Sunday, 13 December 2015

DO NOT use the same name for class and its namespace

In the following code namespace Foo contains class with the same name - Foo:


This causes compiler to issue an error:

Error CS0118: 'Foo' is a namespace but is used like a type

The problem is in that compiler does not know if we are trying to use new on the namespace or on the actual class. To rectify this, we have to use the fully qualified class name (which includes namespace):


In some cases this might not be enough so it is better to avoid using same name for class and for its namespace.

Eric Lippert has a series of blog articles on this topic:

Do not name a class the same as its namespace


Also, here are some SO Q&A:

'namespace used like a type' error
'CompanyName.Foo' is a 'namespace' but is used like a 'type'

Saturday, 12 December 2015

How to set return values for methods returning Task<T>


Non-async method which returns Task<T>


If method is not marked as async and its return type is Task<T>, it has to return object of type Task<T> otherwise compiler issues an error. This is the example of the typical type mismatch error where code:


...causes a compiler error:

Error CS0029: Cannot implicitly convert type 'int' to 'System.Threading.Tasks.Task'

This can be rectified by simply returning expected type:



async method which returns Task<T>


If method is marked as async and its return type is Task<T>, it has to return object of type T, which is int in our case:


...but because async method lacks await in its body, this code generates compiler warning:

Warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

We can await only methods which return Task or Task<T> so this can be fixed by returning value from awaited completed task:


We have to be careful when calling methods returning Task<T>. If not await-ed, they return Task<T>. If awaited, they return object of Task's generic argument type, T. The following code is not awaiting method returning Task<int>:


...which causes compiler error:

Error CS4016: Since this is an async method, the return expression must be of type 'int' rather than 'Task'

Both methods are awaitable because they return object of type Task:


Asynchronous lambda

If you try to await some task in lambda expression like here:



...you will a compiler error:


Error CS4034: The 'await' operator can only be used within an async lambda expression. Consider marking this lambda expression with the 'async' modifier.


The fix is obvious: apply async to lambda - put it just before lambda's parameter list:


Sunday, 9 March 2014

async - await idiom

async-await idiom has been introduced in C# 5.0 and it is basically a syntactic sugar for implementation of task's continuations.

Here are some interesting excerpts from the article "Easier Asynchronous Programming with the New Visual Studio Async CTP" by Eric Lippert, which was published in MSDN Magazine in October 2011:

The work that must come after a particular task is finished is called the continuation of the task.

An await expression (...) means “evaluate this expression to obtain an object representing work that will in the future produce a result. Sign up the remainder of the current method as the callback associated
with the continuation of that task. Once the task is produced and the callback is signed up, immediately return control to my caller.”

Every time an await is encountered, the currently executing method signs up the rest of the method as the thing to do when the current task is complete, and then immediately returns. Somehow each task will complete itself—either by being scheduled to run as an event on the current thread, or because it used an I/O completion thread or worker thread—and will then cause its continuation to “pick up where it left off ” in executing the rest of the method.

Note that the method is now marked with the new async keyword; this is simply an indicator to the compiler that lets it know that in the context of this method, the keyword await is to be treated as a point where the workflow returns control to its caller and picks up again when the associated task is finished.


Asynchronous Programming with Async and Await (MSDN)
async (C# Reference)(MSDN)
await (C# Reference)(MSDN)

Asynchrony in C# 5, Part One (Eric Lippert's blog)

Whenever a task is "awaited", the remainder of the current method is signed up as a continuation of the task, and then control immediately returns to the caller. When the task completes, the continuation is invoked and the method starts up where it was before.

Asynchronous Programming in C# 5.0 part two: Whence await? (Eric Lippert's blog)
Async articles from John Skeet's blog
Async/Await FAQ
What is thread doing after returning from async point? (SO)
What happens to an `awaiting` thread in C# Async CTP?
C# Async Await Cheatsheet

Friday, 28 December 2012

Safe release of resources

If class allocates unmanaged resources (database connections, sockets, window handles, bitmaps...) it has to implement IDisposable interface with a single method Dispose() which deallocates such resources. When user of this class does not need its instance any more, it has to make sure Dispose() is called - even in the case of an exception. This can be achieved by using try-catch-finally block or with using statement:

Some classes in .NET which implement IDisposable have method Close() along with method Dispose(). Dispose() usually calls Close():

...so it's perfectly safe omitting explicit call to Close() when using using statement.

Resources:
Proper use of the IDisposable interface (SO)
close or dispose (SO)
Does Stream.Dispose always call Stream.Close (and Stream.Flush) (SO)

Thursday, 19 April 2012

Logging into file in C#


If this approach is used in WCF service hosted on IIS, we will more likely be interested in the Web Service Application directory which can be obtained by using HostingEnvironment.ApplicationPhysicalPath property - it returns WCF service application's physical path e.g. C:\inetpub\wwwroot\WebServices\MyService.



Make sure that IIS_IUSRS has permission to create, modify and delete files in the directory where WCF service log file resides.


Some features of C#


This is a collection of some features of C# I found useful and interesting, given I am coming from a C++ background.


- it is easy to stringify enum values by using Enum.ToString Method
- it is possible to use strings in switch statement
- In C++, derived class constructor calls base class constructor by stating base class name:

...while in C# keyword base is used:

- C# does not allow multiple inheritance (class cannot inherit multiple base classes)

Abstract Classes

Both in C++ and C# abstract classes are designed to be base classes and can never be instantiated.
In C++, a class is abstract if has at least one pure virtual method.
In C#, a class is abstract if declared with abstract keyword. It may contain abstract methods and properties (they are declared as abstract and don't have implementation).
A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors. Those implementations are method overrides and must be declared with override keyword.
Abstract methods are implicitly virtual.


Auto-Implemented Properties


Auto-implemented properties come very handy for properties with trivial accessors. Compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.

Don't try to implement auto-implemented properties. You'll end up having stack overflow! Example:



Object types and memory storage


In C++ there are POD (Plain Old Data) types (e.g. int, float, pointers, certain struct types,...see further explanations here) and non-POD types. Object of any type can be stored on the stack (e.g. if declared as a local variable) or on the heap (if created with new).

C# uses different type classification: there are value types and reference types. C# doesn't care where are they stored in memory. In C# a new can be used to store (value type) object either on the stack or on the heap.

Further reading:
Type Fundamentals
The Truth About Value Types
The Stack Is An Implementation Detail
C# Heap(ing) Vs Stack(ing) in .NET