Best .net questions in January 2012

Try-catch speeding up my code?

288 votes

I wrote some code for testing the impact of try-catch, but seeing some surprising results.

static void Main(string[] args)
{
    Thread.CurrentThread.Priority = ThreadPriority.Highest;
    Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.RealTime;

    long start = 0, stop = 0, elapsed = 0;
    double avg = 0.0;

    long temp = Fibo(1);

    for (int i = 1; i < 100000000; i++)
    {
        start = Stopwatch.GetTimestamp();
        temp = Fibo(100);
        stop = Stopwatch.GetTimestamp();

        elapsed = stop - start;
        avg = avg + ((double)elapsed - avg) / i;
    }

    Console.WriteLine("Elapsed: " + avg);
    Console.ReadKey();
}

static long Fibo(int n)
{
    long n1 = 1, n2 = 1, fibo = 1;
    n++;

    for (int i = 2; i < n; i++)
    {
        n1 = n2;
        n2 = fibo;
        fibo = n1 + n2;
    }

    return fibo;
}

On my computer, this consistently prints out a value around 0.96..

When I wrap the for loop inside Fibo() with a try-catch block like this:

static long Fibo(int n)
{
    long n1 = 1, n2 = 1, fibo = 1;
    n++;

    try
    {
        for (int i = 2; i < n; i++)
        {
            n1 = n2;
            n2 = fibo;
            fibo = n1 + n2;
        }
    }
    catch {}

    return fibo;
}

Now it consistently prints out 0.69... -- it actually runs faster! But why?

Note: I compiled this using the Release configuration and directly ran the exe (outside Visual Studio).

EDIT: Jon Skeet's excellent analysis shows that try-catch is somehow causing the x86 CLR to use the cpu registers in a more favorable way in this specific case (and I think we're yet to understand why). I confirmed Jon's finding that x64 CLR doesn't have this difference, and that it was faster than the x86 CLR. I also tested using int types inside the Fibo method instead of long types, and then the x86 CLR was as equally fast as the x64 CLR.

One of the Roslyn engineers who specializes in understanding optimization of stack usage took a look at this and reports to me that there seems to be a problem in the interaction between the way the C# compiler generates local variable stores and the way the jit compiler does register scheduling in the corresponding x86 code. The result is suboptimal codegen on the loads and stores of the locals.

For some reason unclear to all of us, the problematic codegen path is avoided when the jitter knows that the block is in a try-protected region.

This is pretty weird. We'll follow up with the jitter team and see if we can get a bug entered so that they can fix this up.

Also, we are working on improvements for Roslyn to the C# and VB compilers' algorithms for determining when locals can be made "ephemeral" -- that is, just pushed and popped on the stack, rather than allocated a specific location on the stack for the duration of the activation. We believe that the jitter will be able to do a better job of register allocation and whatnot if we give it better hints about when locals can be made "dead" earlier.

Thanks for bringing this to our attention, and apologies for the odd behaviour.

Why can I initialize a List like an array in C#?

83 votes

Today I was surprised to find that in C# I can do:

List<int> a = new List<int> { 1, 2, 3 };

Why can I do this? What constructor is called? How can I do this with my own classes? I know that this is the way to initialize arrays but arrays are language items and Lists are simple objects ...

This is part of the collection initializer syntax in .NET. You can use this syntax on any collection you create as long as:

  • It implements IEnumerable (preferably IEnumerable<T>)

  • It has a method named Add(...)

What happens is the default constructor is called, and then Add(...) is called for each member of the initializer.

Thus, these two blocks are roughly identical:

List<int> a = new List<int> { 1, 2, 3 };

And

List<int> temp = new List<int>();
temp.Add(1);
temp.Add(2);
temp.Add(3);
List<int> a = temp;

You can call an alternate constructor if you want, for example to prevent over-sizing the List<T> during growing, etc:

// Notice, calls the List constructor that takes an int arg
// for initial capacity, then Add()'s three items.
List<int> a = new List<int>(3) { 1, 2, 3, }

Note that the Add() method need not take a single item, for example the Add() method for Dictionary<TKey, TValue> takes two items:

var grades = new Dictionary<string, int>
    {
        { "Suzy", 100 },
        { "David", 98 },
        { "Karen", 73 }
    };

Is roughly identical to:

var temp = new Dictionary<string, int>();
temp.Add("Suzy", 100);
temp.Add("David", 98);
temp.Add("Karen", 73);
var grades = temp;

So, to add this to your own class, all you need do, as mentioned, is implement IEnumerable (again, preferably IEnumerable<T>) and create one or more Add() methods:

public class SomeCollection<T> : IEnumerable<T>
{
    // implement Add() methods appropriate for your collection
    public void Add(T item)
    {
        // your add logic    
    }

    // implement your enumerators for IEnumerable<T> (and IEnumerable)
    public IEnumerator<T> GetEnumerator()
    {
        // your implementation
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

Then you can use it just like the BCL collections do:

public class MyProgram
{
    private SomeCollection<int> _myCollection = new SomeCollection<int> { 13, 5, 7 };    

    // ...
}

(For more information, see the MSDN)

How is Math.Pow() implemented in .Net Framework?

68 votes

I was looking for an efficient approach for calculating ab (say a = 2 and b = 50). To start things up, I decided to take a look at the implementation of Math.Pow() function. But in .Net reflector, all I found was this:

[MethodImpl(MethodImplOptions.InternalCall), SecuritySafeCritical]
public static extern double Pow(double x, double y);

Can anyone tell me or point me to some of the resources wherein I can see as what's going on inside when I call Math.Pow() function.

MethodImplOptions.InternalCall

That means that the method is actually implemented in the CLR, written in C++. The just-in-time compiler consults a table with internally implemented methods and compiles the call to the C++ function directly.

Having a look at the code requires the source code for the CLR. You can get that from the SSCLI20 distribution. It was written around the .NET 2.0 time frame, I've found the low-level implementations, like Math.Pow() to be still largely accurate for later versions of the CLR.

The lookup table is located in clr/src/vm/ecall.cpp. The section that's relevant to Math.Pow looks like this:

FCFuncStart(gMathFuncs)
    FCIntrinsic("Sin", COMDouble::Sin, CORINFO_INTRINSIC_Sin)
    FCIntrinsic("Cos", COMDouble::Cos, CORINFO_INTRINSIC_Cos)
    FCIntrinsic("Sqrt", COMDouble::Sqrt, CORINFO_INTRINSIC_Sqrt)
    FCIntrinsic("Round", COMDouble::Round, CORINFO_INTRINSIC_Round)
    FCIntrinsicSig("Abs", &gsig_SM_Flt_RetFlt, COMDouble::AbsFlt, CORINFO_INTRINSIC_Abs)
    FCIntrinsicSig("Abs", &gsig_SM_Dbl_RetDbl, COMDouble::AbsDbl, CORINFO_INTRINSIC_Abs)
    FCFuncElement("Exp", COMDouble::Exp)
    FCFuncElement("Pow", COMDouble::Pow)
    // etc..
FCFuncEnd()

Searching for "COMDouble" takes you to clr/src/classlibnative/float/comfloat.cpp. I'll spare you the code, just have a look for yourself. It basically checks for corner cases, then calls the CRT's version of pow().

The only other implementation detail that's interesting is the FCIntrinsic macro in the table. That's a hint that the jitter may implement the function as an intrinsic. In other words, substitute the function call with a floating point machine code instruction. Which is not the case for Pow(), there is no FPU instruction for it. But certainly for the other simple operations. Notable is that this can make floating point math in C# substantially faster than the same code in C++, check this answer for the reason why.

Btw, the source code for the CRT is also available if you have the full version of VS. vc/crt/src directory. You'll hit the wall on pow() though, Microsoft purchased that code from Intel. Doing a better job than the Intel engineers is unlikely. Although my high-school book's identity was twice as fast when I tried it:

    public static double fasterPow(double x, double y) {
        return Math.Exp(y * Math.Log(x));
    }

C# optional parameters on overridden methods

44 votes

Seems like in .NET Framework there is an issue with optional parameters when you override the method. The output of the code below is: "bbb" "aaa" . But the output I'm expecting is: "bbb" "bbb" .Is there a solution for this. I know it can be solved with method overloading but wondering the reason for this. Also the code works fine in Mono.

class Program
{
    class AAA
    {
        public virtual void MyMethod(string s = "aaa")
        {
            Console.WriteLine(s);
        }

        public virtual void MyMethod2()
        {
            MyMethod();
        }
    }

    class BBB : AAA
    {
        public override void MyMethod(string s = "bbb")
        {
            base.MyMethod(s);
        }

        public override void MyMethod2()
        {
            MyMethod();
        }
    }

    static void Main(string[] args)
    {
        BBB asd = new BBB();
        asd.MyMethod();
        asd.MyMethod2();
    }
}

One thing worth noting here, is that the overridden version is called each time. Change the override to:

public override void MyMethod(string s = "bbb")
{
  Console.Write("derived: ");
  base.MyMethod(s);
}

And the output is:

derived: bbb
derived: aaa

A method in a class can do one or two of the following:

  1. It defines an interface for other code to call.
  2. It defines an implementation to execute when called.

It may not do both, as an abstract method does only the former.

Within BBB the call MyMethod() calls a method defined in AAA.

Because there is an override in BBB, calling that method results in an implementation in BBB being called.

Now, the definition in AAA informs calling code of two things (well, a few others too that don't matter here).

  1. The signature void MyMethod(string).
  2. (For those languages that support it) the default value for the single parameter is "aaa" and therefore when compiling code of the form MyMethod() if no method matching MyMethod() can be found, you may replace it with a call to `MyMethod("aaa").

So, that's what the call in BBB does: The compiler sees a call to MyMethod(), doesn't find a method MyMethod() but does find a method MyMethod(string). It also sees that at the place where it is defined there's a default value of "aaa", so at compile time it changes this to a call to MyMethod("aaa").

From within BBB, AAA is considered the place where AAA's methods are defined, even if overridden in BBB, so that they can be over-ridden.

At run-time, MyMethod(string) is called with the argument "aaa". Because there is a overridden form, that is the form called, but it is not called with "bbb" because that value has nothing to do with the run-time implementation but with the compile-time definition.

Adding this. changes which definition is examined, and so changes what argument is used in the call.

Edit: Why this seems more intuitive to me.

Personally, and since I'm talking of what is intuitive it can only be personal, I find this more intuitive for the following reason:

If I was coding BBB then whether calling or overriding MyMethod(string), I'd think of that as "doing AAA stuff" - it's BBBs take on "doing AAA stuff", but it's doing AAA stuff all the same. Hence whether calling or overriding, I'm going to be aware of the fact that it was AAA that defined MyMethod(string).

If I was calling code that used BBB, I'd think of "using BBB stuff". I might not be very aware of which was originally defined in AAA, and I'd perhaps think of this as merely an implementation detail (if I didn't also use the AAA interface nearby).

The compiler's behaviour matches my intuition, which is why when first reading the question it seemed to me that Mono had a bug. Upon consideration, I can't see how either fulfils the specified behaviour better than the other.

For that matter though, while remaining at a personal level, I'd never use optional parameters with abstract, virtual or overridden methods, and if overriding someone else's that did, I'd match theirs.

Why doesn't the compiler convert var[] to object[] in c#?

26 votes

There is no difference between these two lines, because the compiler, in the second line, understands that it is an array of type int.

var x = new int[] { 1, 2, 3 }; //Fine, x is int[]
var x = new [] { 1, 2, 3 }; //Fine,x is int[]

But why can't I do this with different types? Why doesn't the compiler convert my variable to type object?

var x = new object[] { 1, "df", 5 }; //Fine, x is object[]
var x = new [] { 1, "df", 5 }; //Error! "No best type found for implicity-typed-array"

EDIT:

Thanks for all your answers. But I still wonder, what are the pros and cons to make all expressions that the compiler can't convert to type object? (Because I use var notation which means that it can't be any type. I understand like this.) Why doesn't the compiler find the nearest type of the array members by going up the inheritence tree?

The new [] notation is for saving you to type an explicit type of the array members (or allowing you to create arrays where its elements have an anonymous type), but its type inference is limited in that all elements must share the same type or be implicitly convertible to a common type shared by at least one member. See C# Specification, section 7.6.10.4:

An array creation expression of the third form is referred to as an implicitly typed array creation expression. It is similar to the second form, except that the element type of the array is not explicitly given, but determined as the best common type (§7.5.2.14) of the set of expressions in the array initializer.

The following are examples of implicitly typed array creation expressions:

var a = new[] { 1, 10, 100, 1000 };                       // int[]
var b = new[] { 1, 1.5, 2, 2.5 };                         // double[]
var c = new[,] { { "hello", null }, { "world", "!" } };   // string[,]
var d = new[] { 1, "one", 2, "two" };                     // Error

The last expression causes a compile-time error because neither int nor string is implicitly convertible to the other, and so there is no best common type. An explicitly typed array creation expression must be used in this case, for example specifying the type to be object[]. Alternatively, one of the elements can be cast to a common base type, which would then become the inferred element type.

Key point here is that the “best common type” can only be one of the types already present. As Damien_The_Unbeliever pointed out in a comment: “As Mr. Lippert is fond of pointing out around inference, whenever it's looking for a best common type, it will only return one of the types that is already present - it doesn't go hunting for the most-derived common ancestor.”.

Just because every array could be an object [] doesn't mean it should. From a compiler perspective that'd be a trivial last-resort choice, but a very counter-intuitive one for the developer, I guess.

casting result to float in method returning float changes result

25 votes

I wanted to understand why this code prints False in .net 4.

I wanted to know what exactly what was going on with the cast.

The answer was not "floating point is inaccurate" or "don't do that".

float a(float x, float y)
{
  return ( x * y );
}

float b(float x, float y)
{
  return (float)( x * y );
}

void Main()
{
  Console.WriteLine( a( 10f, 1f/10f ) == b( 10f, 1f/10f ) );
}

PS: This code came from a unit test that cares about floats, not release code that is comparing them. PPS: The unit test allowed me to discover a difference after upgrading from 3.5. It was useful.

David's comment is correct but insufficiently strong. There is no guarantee that doing that calculation twice in the same program will produce the same results.

The C# specification is extremely clear on this point:


Floating-point operations may be performed with higher precision than the result type of the operation. For example, some hardware architectures support an “extended” or “long double” floating-point type with greater range and precision than the double type, and implicitly perform all floating-point operations using this higher precision type. Only at excessive cost in performance can such hardware architectures be made to perform floating-point operations with less precision, and rather than require an implementation to forfeit both performance and precision, C# allows a higher precision type to be used for all floating-point operations. Other than delivering more precise results, this rarely has any measurable effects. However, in expressions of the form x * y / z, where the multiplication produces a result that is outside the double range, but the subsequent division brings the temporary result back into the double range, the fact that the expression is evaluated in a higher range format may cause a finite result to be produced instead of an infinity.


The C# compiler, the jitter and the runtime all have broad lattitude to give you more accurate results than are required by the specification, at any time, at a whim -- they are not required to choose to do so consistently and in fact they do not.

If you don't like that then do not use binary floating point numbers; either use decimals or arbitrary precision rationals.

I don't understand why casting to float in a method that returns float makes the difference it does

Excellent point.

Your sample program demonstrates how small changes can cause large effects. You note that in some version of the runtime, casting to float explicitly gives a different result than not doing so. When you explicitly cast to float, the C# compiler gives a hint to the runtime to say "take this thing out of extra high precision mode if you happen to be using this optimization". As the specification notes, this has a potential performance cost.

That doing so happens to round to the "right answer" is merely a happy accident; the right answer is obtained because in this case losing precision happened to lose it in the correct direction.

How is .net 4 different?

You ask what the difference is between 3.5 and 4.0 runtimes; the difference is clearly that in 4.0, the jitter chooses to go to higher precision in your particular case, and the 3.5 jitter chooses not to. That does not mean that this situation was impossible in 3.5; it has been possible in every version of the runtime and every version of the C# compiler. You've just happened to run across a case where, on your machine, they differ in their details. But the jitter has always been allowed to make this optimization, and always has done so at its whim.

The C# compiler is also completely within its rights to choose to make similar optimizations when computing constant floats at compile time. Two seemingly-identical calculations in constants may have different results depending upon details of the compiler's runtime state.

More generally, your expectation that floating point numbers should have the algebraic properties of real numbers is completely out of line with reality; they do not have those algebraic properties. Floating point operations are not even associative; they certainly do not obey the laws of multiplicative inverses as you seem to expect them to. Floating point numbers are only an approximation of real arithmetic; an approximation that is close enough for, say, simulating a physical system, or computing summary statistics, or some such thing.

How to handle a day that starts from 06:00 and ends at 30:00

24 votes

I am working with a case where the client has a 30 hour day.

The day starts at 6 am and then goes around to 6 am the next day, but when they come to 1 am the next day, they take it as 25:00 hours. 2 am will be 26:00 hours and so forth...

Now, i want to know, is there a way to handle this in c#'s DateTime class or do i need to do it the long way and split it all up?

UPDATE:

It's a Media Agency in Australia. Just to explain again, the day starts at 06:00 am (12 Jan 2012), when it comes to midnight it will be 24:00. Now when it is 01:00 am (13 Jan 2012) the next day, the client takes it as 25:00 hours (12 Jan 2012).

They still have 24 hours in a day. The only difference is that their day starts at 6 am and not 00 hours like us.

UPDATE:

XML representation of a typical program i need to work with. Note: Removed CHANNEL_CODE and CHANNEL_NAME.

 <PROGRAMME>
  <PROGRAMME_ID>1</PROGRAMME_ID>
  <PROGRAMME_NAME>Mass For You At Home</PROGRAMME_NAME>
  <CHANNEL_CODE>SomeCode</CHANNEL_CODE>
  <CHANNEL_NAME>SomeChannel</CHANNEL_NAME>
  <TX_DATE>20120101</TX_DATE>
  <START_TIME>06:00</START_TIME>
  <DURATION>1800</DURATION>
  <AGENCY_AVAIL>C</AGENCY_AVAIL>
  <SALES_AVAIL>90</SALES_AVAIL>
  <SSB>N</SSB>
 </PROGRAMME>
</PROGRAMME>


<PROGRAMME>
  <PROGRAMME_ID>2</PROGRAMME_ID>
  <PROGRAMME_NAME>Home Shopping</PROGRAMME_NAME>
  <CHANNEL_CODE>SomeCode</CHANNEL_CODE>
  <CHANNEL_NAME>SomeChannel</CHANNEL_NAME>
  <TX_DATE>20120101</TX_DATE>
  <START_TIME>26:00</START_TIME>
  <DURATION>1800</DURATION>
  <AGENCY_AVAIL>C</AGENCY_AVAIL>
  <SALES_AVAIL>0</SALES_AVAIL>
  <SSB>N</SSB>
 </PROGRAMME>

So, is there maybe a way to adjust the DateTime class to start at 06:00 and end at 30:00?

This sounds a bit like the situation where you have a business that covers multiple timezones - it's possible, then, to have a continuous day that is longer than 24 hours.

However, this doesn't mean that you have to adjust the length of a day - a day is an international convention, and, unless Jon Skeet actually decides to use the giant gravity gun he has undoubedly built (in a day ;-) and uses it to change the rotational speed of the earth, extending the alternating period of light and darkness we refer to as a day, your best bet is to probably use the concept of a shift or timeslot;

A shift (in your case, a timeslot!) has a work day, a length, and a timezone. You can then:

  • Sum all of the hours an advert was shown for a workday (sum[length] where date = workday)
  • Sum all of the hours an advert was shown for a timezone (sum[length] where timezone = x group by workday
  • Sum all of the hours an advert was on for a particular astronomical date (work out the number of hours between the workday.starttime and midnight versus the length)

It's best not to refer to these as days as it confuses straightforward terminology.

In your instance, you aren't even bothered about the timezone. I think all you really need is the date/time the advert timeslot is due to start, and the number of hours it is due to be shown for.

EDIT: In the case of your XML, you can still use the above concept. You can either:

1) Clean it up when you get the XML and store it as a 'proper' datetime - so work out what the UTC starttime is and use the duration

2) Create a class that just converts this to normal datetime representation with the length. The benefit of this approach is that you can also go the other way, back to the source convention.

Realistically, I think that's really all you need.

For example, in the xml above, you could create a class; something like this should do the trick:

public class AdvertDate{

    public DateTime TransmissionDate { get; set;} //Store as 06:00 on the TX_Date

    public int AdvertStartTime { get; set; } //Store as 0 - 30

    public int Duration { get; set; } //Store as 18 - assuming whole numbers so change if needed        
    public DateTime RealDate {
        get{
            return TransmissionDate.AddHours(AdvertStartTime);
        }
    }


    public AdvertDate(){

    }

    public AdvertDate(DateTime transmissionDate, int advertStartTime, int duration){
        TransmissionDate = transmissionDate;
        AdvertStartTime = advertStartTime;
        Duration = duration;
    }


    public AdvertDate ConvertRealDateTimeToAdvertDate(DateTime realDateTime, int advertDuration){

        if(realDateTime.Hour < 6)
        {
            DateTime  advertDateTime = realDateTime.AddDays(-1).Date.AddHours(6);

            return new AdvertDate(advertDateTime, 24+realDateTime.Hour, advertDuration);
        }
        else{
            return new AdvertDate(realDateTime.Date.AddHours(6), realDateTime.Hour, advertDuration);
        }

    }


    public void LoadFromXml(){
        //Xml Loading here (or in a dedicated class or wherever)
    }



}

Simulate tearing a double in C#

18 votes

I'm running on a 32-bit machine and I'm able to confirm that long values can tear using the following code snippet which hits very quickly.

        static void TestTearingLong()
        {
            System.Threading.Thread A = new System.Threading.Thread(ThreadA);
            A.Start();

            System.Threading.Thread B = new System.Threading.Thread(ThreadB);
            B.Start();
        }

        static ulong s_x;

        static void ThreadA()
        {
            int i = 0;
            while (true)
            {
                s_x = (i & 1) == 0 ? 0x0L : 0xaaaabbbbccccddddL;
                i++;
            }
        }

        static void ThreadB()
        {
            while (true)
            {
                ulong x = s_x;
                Debug.Assert(x == 0x0L || x == 0xaaaabbbbccccddddL);
            }
        }

But when I try something similar with doubles, I'm not able to get any tearing. Does anyone know why? As far as I can tell from the spec, only assignment to a float is atomic. The assignment to a double should have a risk of tearing.

    static double s_x;

    static void TestTearingDouble()
    {
        System.Threading.Thread A = new System.Threading.Thread(ThreadA);
        A.Start();

        System.Threading.Thread B = new System.Threading.Thread(ThreadB);
        B.Start();
    }

    static void ThreadA()
    {
        long i = 0;

        while (true)
        {
            s_x = ((i & 1) == 0) ? 0.0 : double.MaxValue;
            i++;

            if (i % 10000000 == 0)
            {
                Console.Out.WriteLine("i = " + i);
            }
        }
    }

    static void ThreadB()
    {
        while (true)
        {
            double x = s_x;

            System.Diagnostics.Debug.Assert(x == 0.0 || x == double.MaxValue);
        }
    }

static double s_x;

It is much harder to demonstrate the effect when you use a double. The CPU uses dedicated instructions to load and store a double, respectively FLD and FSTP. It is much easier with long since there is no single instruction that load/stores a 64-bit integer in 32-bit mode. To observe it you need to have the variable's address misaligned so it straddles the cpu cache line boundary.

That will never happen with the declaration you used, the JIT compiler ensures that the double is aligned properly, stored at an address that's a multiple of 8. You could store it in a field of a class, the GC allocator only aligns to 4 in 32-bit mode. But that's a crap shoot.

Best way to do it is by intentionally mis-aligning the double by using a pointer. Put unsafe in front of the Program class and make it look similar to this:

    static double* s_x;

    static void Main(string[] args) {
        var mem = Marshal.AllocCoTaskMem(100);
        s_x = (double*)((long)(mem) + 28);
        TestTearingDouble();
    }
ThreadA:
            *s_x = ((i & 1) == 0) ? 0.0 : double.MaxValue;
ThreadB:
            double x = *s_x;

This still won't guarantee a good misalignment (hehe) since there's no way to control exactly where AllocCoTaskMem() will align the allocation relative to the start of the cpu cache line. And it depends on the cache associativity in your cpu core (mine is a Core i5). You'll have to tinker with the offset, I got the value 28 by experimentation. The value should be divisible by 4 but not by 8 to truly simulate the GC heap behavior. Keep adding 8 to the value until you get the double to straddle the cache line and trigger the assert.

To make it less artificial you'll have to write a program that stores the double in field of a class and get the garbage collector to move it around in memory so it gets misaligned. Kinda hard to come up with a sample program that ensures this happens.

Also note how your program can demonstrate a problem called false sharing. Comment out the Start() method call for thread B and note how much faster thread A runs. You are seeing the cost of the cpu keeping the cache line consistent between the cpu cores. Sharing is intended here since the threads access the same variable. Real false sharing happens when threads access different variables that are stored in the same cache line. This is otherwise why alignment matters, you can only observe the tearing for a double when part of it is in one cache line and part of it is in another.

Serializing null in JSON.NET

17 votes

When serializing arbitrary data via JSON.NET, any property that is null is written to the JSON as

"propertyName" : null

This is correct, of course.

However I have a requirement to automatically translate all nulls into the default empty value, e.g. null strings should become String.Empty, null int?s should become 0, null bool?s should be false, and so on.

NullValueHandling is not helpful, since I dont want to Ignore nulls, but neither do I want to Include them (Hmm, new feature?).

So I turned to implementing a custom JsonConverter.
While the implementation itself was a breeze, unfortunately this still didnt work - CanConvert() is never called for a property that has a null value, and therefore WriteJson() is not called either. Apparently nulls are automatically serialized directly into null, without the custom pipeline.

For example, here is a sample of a custom converter for null strings:

public class StringConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(string).IsAssignableFrom(objectType);
    }

    ...
    public override void WriteJson(JsonWriter writer, 
                object value, 
                JsonSerializer serializer)
    {
        string strValue = value as string;

        if (strValue == null)
        {
            writer.WriteValue(String.Empty);
        }
        else
        {
            writer.WriteValue(strValue);
        }
    }
}

Stepping through this in the debugger, I noted that neither of these methods are called for properties that have a null value.

Delving into JSON.NET's sourcecode, I found that (apparently, I didnt go into a lot of depth) there is a special case checking for nulls, and explictly calling .WriteNull().

For what it's worth, I did try implementing a custom JsonTextWriter and overriding the default .WriteNull() implementation...

public class NullJsonWriter : JsonTextWriter
{
    ... 
    public override void WriteNull()
    {
        this.WriteValue(String.Empty);
    }
}

However, this can't work well, since the WriteNull() method knows nothing about the underlying datatype. So sure, I can output "" for any null, but that doesnt work well for e.g. int, bool, etc.

So, my question - short of converting the entire data structure manually, is there any solution or workaround for this?

Okay, I think I've come up with a solution (my first solution wasn't right at all, but then again I was on the train). You need to create a special contract resolver and a custom ValueProvider for Nullable types. Consider this:

public class NullableValueProvider : IValueProvider
{
    private readonly object _defaultValue;
    private readonly IValueProvider _underlyingValueProvider;


    public NullableValueProvider(MemberInfo memberInfo, Type underlyingType)
    {
        _underlyingValueProvider = new DynamicValueProvider(memberInfo);
        _defaultValue = Activator.CreateInstance(underlyingType);
    }

    public void SetValue(object target, object value)
    {
        _underlyingValueProvider.SetValue(target, value);
    }

    public object GetValue(object target)
    {
        return _underlyingValueProvider.GetValue(target) ?? _defaultValue;
    }
}

public class SpecialContractResolver : DefaultContractResolver
{
    protected override IValueProvider CreateMemberValueProvider(MemberInfo member)
    {
        if(member.MemberType == MemberTypes.Property)
        {
            var pi = (PropertyInfo) member;
            if (pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition() == typeof (Nullable<>))
            {
                return new NullableValueProvider(member, pi.PropertyType.GetGenericArguments().First());
            }
        }
        else if(member.MemberType == MemberTypes.Field)
        {
            var fi = (FieldInfo) member;
            if(fi.FieldType.IsGenericType && fi.FieldType.GetGenericTypeDefinition() == typeof(Nullable<>))
                return new NullableValueProvider(member, fi.FieldType.GetGenericArguments().First());
        }

        return base.CreateMemberValueProvider(member);
    }
}

Then I tested it using:

class Foo
{
    public int? Int { get; set; }
    public bool? Boolean { get; set; }
    public int? IntField;
}

And the following case:

[TestFixture]
public class Tests
{
    [Test]
    public void Test()
    {
        var foo = new Foo();

        var settings = new JsonSerializerSettings { ContractResolver = new SpecialContractResolver() };

        Assert.AreEqual(
            JsonConvert.SerializeObject(foo, Formatting.None, settings), 
            "{\"IntField\":0,\"Int\":0,\"Boolean\":false}");
    }
}

Hopefully this helps a bit...

Edit – Better identification of the a Nullable<> type

Edit – Added support for fields as well as properties, also piggy-backing on top of the normal DynamicValueProvider to do most of the work, with updated test

It is wrong to use special characters in C# source code, such as "ñ"?

17 votes

Recently, using C#, I just declared a method parameters using the Latin character ñ, and I tried to build (compile) my entire solution and it works, therefore I was able to execute my program. But I'm curious to know if it is wrong to use special characters such as Latin characters in a source code written in C#? If it is wrong, why?

Besides it is more legible and universal to write code in English, are there any other reason to not use special characters in a C# source code?

Let me break this down into several questions.

Is it legal according to the specification to use non-Roman letters in C# identifiers, strings, and so on?

Yes, absolutely. Any character that the Unicode specification classifies as a letter is legal. See the specification for the exact details.

Are there any technical issues regarding non-Roman letters in C# programs?

Yes, there are a few. As you are probably aware, you can both "statically" and "dynamically" link code into an application, and the compiler is an application. We've had problems in the past where the compiler had a statically-linked-in old version of the Unicode classification algorithm, and the editor had a dyamically-linked-in current version, and now the editor and the compiler can disagree on what is a legal letter, which can cause user confusion. However, the accented Latin characters you mention have been in the Unicode standard so long that they are unlikely to cause any sort of problem.

Moreover, a lot of people still use old-fashioned editors; I learned how to program at WATCOM back in the late 1980's and I still frequently use WATCOM VI as my editor. I can sometimes code faster in it than I can in Visual Studio because my fingers are just really good at it after 23 years of practice. (Though these days I use Visual Studio for almost everything.) Obviously an editor written in the 1980's is going to have a problem with Unicode.

Are there any non-technical issues regarding non-Roman letters in C# programs?

Obviously, yes. I personally would rather use Greek letters for generic type parameters, for instance:

class List<τ> : IEnumerable<τ>

or when implementing mathematical code:

degrees = 180.0 * radians / π;

But I resist the urge in deference to my coworkers who do not particularly want to be cutting and pasting, or learning arcane key combinations, just to edit my code.

Why does passing null to a params method results in a null parameter array?

17 votes

I have a method that uses the params keyword, like so:

private void ParamsMethod(params string[] args)
{
    // Etc...
}

Then, I call the method using various combinations of arguments:

                            // Within the method, args is...
ParamsMethod();             // - a string array with no elements
ParamsMethod(null);         // - null (Why is this?)
ParamsMethod((string)null); // - a string array with one element: null
ParamsMethod(null, null);   // - a string array with two elements: null and null
ParamsMethod("s1");         // - a string array with one element: "s1"
ParamsMethod("s1", "s2");   // - a string array with two elements: "s1" and "s2"

I understand all of the cases, except for the second one. Can someone explain why ParamsMethod(null) causes args to be null, instead of an array with one null element?

A params parameter is only meant to provide a convenient way of specifying values - you can still pass an array reference directly.

Now, null is convertible to either string[] or string, so both interpretations are valid - it's up to the spec which is preferred. The spec states in section 10.6.1.4 that:

  • The argument given for a parameter array can be a single expression that is implicitly convertible to the parameter array type. In this case, the parameter array acts precisely like a value parameter.

  • Alternatively, [...]

In other words, the compiler checks to see whether the argument is valid as the "normal" parameter type first, and only builds an array if it absolutely has to.

How to make my application be considered as a communication program in Windows

16 votes

I'm making a program that uses the Speech library and I'd like to get all other sounds muted or reduced when the lady is talking.

I've been looking for a way to mute other applications manually, but I've seen an option in Windows in the communication tab (inside the sound options) that mentions that window can manage this for me. Like in this picture:

enter image description here

So basically, what does it take for my application to be considered as a communication application (such as Skype)?

I believe the communication apps are implementing something related to the IAudioVolumeDuckNotification interface. The C++ example provided also references WM_VOLUME_DUCK and WM_VOLUME_UNDUCK windows messages which may be enough (but don't appear to be google-able or documented).

UPDATE

The .NET Core Audio API project on CodePlex appears to provide a .NET wrapper.

UPDATE

A sample C++ implementation of IAudioVolumeDuckNotification as well as an example of notifying the ducked state can be found in the MSDN DuckingMediaPlayer sample application. It actually works (I tried it). A combination of PInvoke'ing a couple methods and the .NET wrapper for the interface should be enough to get you on your way.

Process.WaitForExit inconsistent across different machines

15 votes

This code runs as expected on a large number of machines. However on one particular machine, the call to WaitForExit() seems to be ignored, and in fact marks the process as exited.

static void Main(string[] args)
{
    Process proc = Process.Start("notepad.exe");
    Console.WriteLine(proc.HasExited); //Always False
    proc.WaitForExit(); //Blocks on all but one machines
    Console.WriteLine(proc.HasExited); //**See comment below
    Console.ReadLine();
}

Note that unlike a similar question on SO, the process being called is notepad.exe (for testing reasons), so it is unlikely the fault lies with it - i.e. it is not spawning a second sub-process and closing. Even so, it would not explain why it works on all the other machines.

On the problem machine, the second call to Console.WriteLine(proc.HasExited)) returns true even though notepad is still clearly open, both on the screen and in the task manager.

The machine is running Windows 7 and .NET 4.0.

My question is; what conditions on that particular machine could be causing this? What should I be checking?

Edit - Things I've tried so far / Updates / Possibly relevant info:

  • Reinstalled .NET.
  • Closed any processes I don't know in task manager.
  • Windows has not yet been activated on this machine.
  • Following advice in the comments, I tried getting the 'existing' process Id using GetProcessesByName but that simply returns an empty array on the problem machine. Therefore, it's hard to say the problem is even with WaitForExit, as the process is not returned by calling GetProcessesByName even before calling WaitForExit.
  • On the problem machine, the resulting notepad process's ParentID is the ID of the notepad process the code manually starts, or in other words, notepad is spawning a child process and terminating itself.

The problem is that by default Process.StartInfo.UseShellExecute is set to true. With this variable set to true, rather than starting the process yourself, you are asking the shell to start it for you. That can be quite useful- it allows you to do things like "execute" an HTML file (the shell will use the appropriate default application).

Its not so good when you want to track the application after executing it (as you found), because the launching application can sometimes get confused about which instance it should be tracking.

The inner details here of why this happens are probably beyond my capabilities to answer- I do know that when UseShellExecute == true, the framework uses the ShellExecuteEx Windows API, and when it UseShellExecute == false, it uses CreateProcessWithLogonW, but why one leads to trackable processes and the other doesn't I don't know, as they both seem to return the process ID.

EDIT: After a little digging:

This question pointed me to the SEE_MASK_NOCLOSEPROCESS flag, which does indeed seem to be set when using ShellExecute. The documentation for the mask value states:

In some cases, such as when execution is satisfied through a DDE conversation, no handle will be returned. The calling application is responsible for closing the handle when it is no longer needed.

So it does suggest that returning the process handle is unreliable. I still have not gotten deep enough to know which particular edge case you might be hitting here though.

Should IDisposable.Dispose() implementations be idempotent?

15 votes

The Microsoft.NET framework provides the IDisposable interface which requires an implementation of void Dispose() method. It's purpose is to enable manual, or scope-based releasing of expensive resources an IDisposable implementation may have allocated. Examples include database collections, streams and handles.

My question is, should the implementation of the Dispose() method be idempotent - when called more than once on the same instance, the instance to be 'disposed of' only once, and subsequent calls not to throw exceptions. In Java, most of the objects that have similar behavior (again streams and database connections) are idempotent for their close() operation, which happens to be the analogue for the Dispose() method. However, my personal experience with .NET (and Windows Forms in particular), shows that not all implementations (that are part of the .NET framework itself) are idempotent, therefore subsequent calls throw an ObjectDisposedException. This really confuses me on how a disposable object's implementation should be approached. Is there a common answer for the scenario, or is it dependent on the concrete context of the object and its usage?

should the implementation of the Dispose() method be idempotent

Yes, it should. There is no telling how many times it will be called.

From Implementing a Dispose Method on MSDN:

a Dispose method should be callable multiple times without throwing an exception.

An object with a good implementation of IDispose will have a boolean field flag indicating if it has been disposed of already and on subsequent calls do nothing (as it was already disposed).

codepad for c#?

14 votes

Possible Duplicate:
Is there a place I can run C# code online?

I recall but am having trouble finding a website where you can enter C# code snippets for quick testing (similar to codepad). This is in lieu of opening a console app and running the test code there. Can someone provide the link?

It is not a website, but for executing code snippets (C#, SQL, F#, ...) quickly, I usually use LINQPad.

Is String.Equals(string1.Substring(0, x), string2) better than string1.StartsWith(string2)?

14 votes

I am using string comparisons to test URL paths using StringComparison.OrdinalIgnoreCase.

MSDN gives the following string comparison advice HERE, but does not clarify WHY:

MSDN Example (half-way down the above page):

public static bool IsFileURI(string path) 
{
   path.StartsWith("FILE:", StringComparison.OrdinalIgnoreCase);
   return true;
}

MSDN Advice:

"However, the preceding example uses the String.StartsWith(String, StringComparison) method to test for equality. Because the purpose of the comparison is to test for equality instead of ordering the strings, a better alternative is to call the Equals method, as shown in the following example."

public static bool IsFileURI(string path)
{
   if (path.Length < 5) return false;

   return String.Equals(path.Substring(0, 5), "FILE:", 
                    StringComparison.OrdinalIgnoreCase);
}

QUESTION: Why does MSDN suggest the second example is better?

Discussion points:

  1. Clearly the return true; in the first example is a bug and should be return path.StartsWith(...);. We can safely ignore this as a bug as the VB code is correct.

  2. Creation of a substring prior to comparing for equality would appear to only use another memory resource than just calling String.StartsWith().

  3. The Length < 5 test is a nice short-circuit, however it could be used with the prior code just the same.

  4. The second example could be construed as clearer code, but I am concerned with performance. The creation of the substring seems unnecessary.

Looking at the StartsWith method using dotPeek, it eventually calls an internal comparison function that compares the entire string, and returns a boolean result based on the return value of that comparison:

return TextInfo.CompareOrdinalIgnoreCaseEx(this, 0, value, 0, value.Length, value.Length) == 0;

String.Equals calls:

return TextInfo.CompareOrdinalIgnoreCase(this, value) == 0;

CompareOrdinalIgnoreCase calls a private method, which dotPeek doesn't show, but my hunch is that the overload called by StartsWith traverses the entire string while the overload called by Equals stops as soon as equality can be determined.

If performance is a concern, try measuring both with values that will be typical for your application.


Out of curiousity, I tried measuring the two, and it does seem that Equals is noticeably faster. When I run the code below using a release build, Equals is nearly twice as fast as StartsWith:

using System;
using System.Diagnostics;

namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var url = "http://stackoverflow.com/questions/8867710/is-string-equalsstring1-substring0-x-string2-better-than-string1-startswit";
            var count = 10000000;
            var http = false;

            Stopwatch sw = Stopwatch.StartNew();

            for (int i = 0; i < count; i++)
            {
                http = url.StartsWith("http:", StringComparison.OrdinalIgnoreCase);
            }

            sw.Stop();

            Console.WriteLine("StartsWith: {0} ms", sw.ElapsedMilliseconds);

            sw.Restart();

            for (int i = 0; i < count; i++)
            {
                http = string.Equals(url.Substring(0, 5), "http:", StringComparison.OrdinalIgnoreCase);
            }

            sw.Stop();

            Console.WriteLine("Equals: {0} ms", sw.ElapsedMilliseconds);

            Console.ReadLine();
        }
    }
}

Get 4 max numbers from a List<int> use lambda expression

13 votes

this is my list:

List<int> numbers=new List<int> { 12, 5, -8, 4, 7, 28, 3, 22 };

How can I get 4 maximum numbers by lambda: I need this ones: {28, 22, 12, 7}

Use:

var result = numbers.OrderByDescending(n => n).Take(4);

comment between else and {

10 votes

I just started using Razor instead of the WebForms-ViewEngine. Now in my Razor-View i have something like this:

@{
  int i = 42;
  string text;
  if (i == 42)
  {
    text = "i is 42!";
  }
  else //i is not 42 //<- Error here
  {
    text = "i is something else";
  }
}

I get a warning and at runtime it get an exception in the else line:

Expected a "{" but found a "/". Block statements must be enclosed in "{" and "}". You cannot use single-statement control-flow statements in CSHTML pages.

Apparently the compiler doesn't like comments between the else and the {. I also tried commenting with @* and /*, which gave similar error-messages.

Is there anyway to make a comment in razor like I want it?


Disclaimer:

Yes i know i could fix it simply like this:

@{
  int i = 42;
  string text;
  if (i == 42)
  {
    text = "i is 42!";
  }
  else
  { //i is not 42
    text = "i is something else";
  }
}

However it doesn't fit our coding guidelines and having the comment on the same line makes my intentions more clear.

That's how the Razor parser is built. You could always submit a bug/feature request on MS connect if you don't like the way it is and hope that people will vote for it and it will be fixed/implemented in a future version of the parser. Personally I wouldn't because I don't care (see below why).

This being said, why care? I mean you are not supposed to write code in a Razor page. A Razor page is intended to be used as a view. In ASP.NET MVC a view is used to display some information from the view model that is passed to it from the controller action. Markup primary, mixed with HTML helpers and displaying information from the view model. But C# code is a no no. So what you call code and what you have shown in your question has strictly nothing to do in a Razor view.

Do asynchronous operations in ASP.NET MVC use a thread from ThreadPool on .NET 4

8 votes

I have too many misunderstandings in my mind about asynchronous operations on ASP.NET MVC.

I always hear this sentence: Application can scale better if operations run asynchronously

And I heard this kind of sentences a lot as well: if you have a huge volume of traffic, you may be better off not performing your queries asynchronously - consuming 2 extra threads to service one request takes resources away from other incoming requests.

I think those two sentences are inconsistent.

I do not have much information about how threadpool works on ASP.NET but I know that threadpool has a limited size for threads. So, the second sentence has to be related to this issue.

And I would like to know if asynchronous operations in ASP.NET MVC uses a thread from ThreadPool on .NET 4?

For example, when we implement a AsyncController, how does the app structures? If I get huge traffic, is it a good idea to implement AsyncController?

Is there anybody out there who can take this black curtain away in front of my eyes and explain me the deal about asynchrony on ASP.NET MVC 3 (NET 4)?

Edit:

I have read this below document nearly hundreds of times and I understand the main deal but still I have confusion because there are too much inconsistent comment out there.

Using an Asynchronous Controller in ASP.NET MVC

Edit:

Let's assume I have controller action like below (not an implementation of AsyncController though):

public ViewResult Index() { 

    Task.Factory.StartNew(() => { 
        //Do an advanced looging here which takes a while
    });

    return View();
}

As you see here, I fire an operation and forget about it. Then, I return immediately without waiting it be completed.

In this case, does this have to use a thread from threadpool? If so, after it completes, what happens to that thread? Does GC comes in and clean up just after it completes?

Edit:

For the @Darin's answer, here is a sample of async code which talks to database:

public class FooController : AsyncController {

    //EF 4.2 DbContext instance
    MyContext _context = new MyContext();

    public void IndexAsync() { 

        AsyncManager.OutstandingOperations.Increment(3);

        Task<IEnumerable<Foo>>.Factory.StartNew(() => { 

           return 
                _context.Foos;
        }).ContinueWith(t => {

            AsyncManager.Parameters["foos"] = t.Result;
            AsyncManager.OutstandingOperations.Decrement();
        });

        Task<IEnumerable<Bars>>.Factory.StartNew(() => { 

           return 
                _context.Bars;
        }).ContinueWith(t => {

            AsyncManager.Parameters["bars"] = t.Result;
            AsyncManager.OutstandingOperations.Decrement();
        });

        Task<IEnumerable<FooBar>>.Factory.StartNew(() => { 

           return 
                _context.FooBars;
        }).ContinueWith(t => {

            AsyncManager.Parameters["foobars"] = t.Result;
            AsyncManager.OutstandingOperations.Decrement();
        });
    }

    public ViewResult IndexCompleted(
        IEnumerable<Foo> foos, 
        IEnumerable<Bar> bars,
        IEnumerable<FooBar> foobars) {

        //Do the regular stuff and return

    }
}

Here's an excellent article I would recommend you reading to better understand asynchronous processing in ASP.NET (which is what asynchronous controllers basically represent).

Let's first consider a standard synchronous action:

public ActionResult Index()
{
    // some processing
    return View();
}

When a request is made to this action a thread is drawn from the thread pool and the body of this action is executed on this thread. So if the processing inside this action is slow you are blocking this thread for the entire processing, so this thread cannot be reused to process other requests. At the end of the request execution the thread is returned to the thread pool.

Now let's take an example of the asynchronous pattern

public void IndexAsync()
{
    // perform some processing
}

public ActionResult IndexCompleted(object result)
{
    return View();
}

When a request is sent to the Index action, a thread is drawn from the thread pool and the body of the IndexAsync method is executed. Once the body of this method finishes executing, the thread is returned to the thread pool. Then using the standard AsyncManager.OutstandingOperations once you signal the completion of the async operation, another thread is drawn from the thread pool and the body of the IndexCompleted action is executed on it and the result rendered to the client.

So what we can see in this pattern is that a single client HTTP request could be executed by two different threads.

Now the interesting part happens inside the IndexAsync method. If you have a blocking operation inside it, you are totally wasting the whole purpose of the asynchronous controllers because you are blocking the worked thread (remember that the body of this action is executed on a thread drawn from the thread pool).

So when can we take real advantage of asynchronous controllers you might ask?

IMHO we can gain most when we have I/O intensive operations (such as database and network calls to remote services). If you have a CPU intensive operation, asynchronous actions won't bring you much benefit.

So why can we gain benefit from I/O intensive operations? Because we could use I/O Completion Ports. IOCP are extremely powerful because you do not consume any thread or resource on the server during the execution of the entire operation.

How they work?

Suppose that we want to download the contents of a remote web page using the WebClient.DownloadStringAsync method. You call this method which will register an IOCP within the operating system and return immediately. During the processing of the entire request, no threads are consumed on your server. Everything happens on the remote server. This could take lots of time but you don't care as you are not jeopardizing your worker threads. Once a response is received the IOCP is signaled, a thread is drawn from the thread pool and the callback is executed on this thread. But as you can see during the entire processing we have not monopolized any thread.

Same stands true with methods such as FileStream.BeginRead, SqlCommand.BeginExecute, ...

What about parallelizing multiple database calls? Suppose that you had a synchronous controller action in which you performed 4 blocking database calls in sequence. It's easy to calculate that if each database call takes 200ms your controller action will take roughly 800ms to execute.

If you don't need to run those calls sequentially would parallelizing them improve performance?

That's the big question which is not easy to answer. Maybe yes, maybe not. It will entirely depend on how you implement those database calls. If you use async controllers and I/O Completion ports as discussed previously you will boost the performance of this controller action and on other actions as well as you won't be monopolizing worker threads.

On the other hand if you implement them poorly (with a blocking database call performed on a thread from the thread pool), you will basically lower the total time of execution of this action to roughly 200ms but you would have consumed 4 worker threads so you might have degraded the performance of other requests which might become starving because of missing threads in the pool to process them.

So it is very difficult and you don't feel ready to perform extensive tests on your application do not implement asynchronous controllers as chances are that you will do more damage than benefit. Implement them only if you have a reason to do so: for example you have identified that standard synchronous controller actions are a bottleneck to your application (after performing extensive load tests and measurements of course).

Now let's consider your example:

public ViewResult Index() { 

    Task.Factory.StartNew(() => { 
        //Do an advanced looging here which takes a while
    });

    return View();
}

When a request is received for the Index action a thread is drawn from the thread pool to executed its body. Bit its body only schedules a new task using TPL. So the action execution ends and the thread is returned to the thread pool. Except that, TPL uses threads from the thread pool to perform their processing. So even if the original thread was returned to the thread pool, you have drawn another thread from this pool to execute the body of the task. So you have jeopardized 2 threads from your precious pool.

Now let's consider the following:

public ViewResult Index() { 

    new Thread(() => { 
        //Do an advanced looging here which takes a while
    }).Start();

    return View();
}

In this case we are manually spawning a thread. In this case the execution of the body of the Index action might take slightly longer (because spawning a new thread is more expensive than drawing one from an existing pool). But the execution of the advanced logging operation will be done on a thread which is not part of the pool. So we are not jeopardizing threads from the pool which remain free for serving another requests.

Binding to X Y coordinates of element on WPF Canvas

7 votes

I have a Canvas with 2 "dots" drawn on it. See this (simplified) code:

<Canvas> 
    <Ellipse />
    <Ellipse />
    <Canvas.RenderTransform>
        <RotateTransform x:Name="rotateEllipse" />
    </Canvas.RenderTransform>
</Canvas>

As you can see, I want to rotate the canvas using the given RotateTransform.

Next, I want to put a TextBlock near to each Ellipse (a label). However, I don't want to include this TextBlock into the Canvas because it will then rotate also. I want the text to remain horizontal.

Any idea how to solve this in an elegant way?

Something like this, should work for you

<TextBlock RenderTransform="{Binding RelativeSource={RelativeSource AncestorType=Canvas},
                                                      Path=RenderTransform.Inverse}"/>

Assign to text box transformation matrix an inverse of the transformation matrix of the Canvas.