Thursday, September 24, 2015

Format Strings to Use a Percent Sign (%) Without the Formatter Multiplying the Value by 100

I had an application that needed to display a value with a percent sign (%) after it. The value had already been converted from decimal to integer, or in other words had already been multiplied by 100. I did not have the option to just append a % at the end of the string. All the object gave me access to was the format. I tried "#0%", which gave me what I wanted, except that it multiplied the value by 100, so 20% became 2000%.

After a little research I found that using an escape character gave me what I wanted.

ToString("#0\\%")

Wednesday, September 9, 2015

C# Equivalent of DoEvents

I have been looking for a long time for an equivalent to Visual Basic's DoEvents statement.

DoEvents allows your code to yield execution to other threads in order to share processing time.  This could be do in a loop to allow you to process an iteration of the loop and when done yield.  This is often done to attempt to keep the UI responsive.  After each iteration you would call DoEvents thus allowing the UI some processing time.

I was studying today about multi threading and asynchronous processing when I came across some code that did a loop and called Thread.Sleep(0) at the end of each iteration.  Supposedly this yields execution without causing the loop to execute longer, since the sleep is for zero milliseconds.  Since the thread goes to sleep, other threads can then take over and release control when it is done.

I think you can use DoEvents in C# by using the the Visual Basic library, but from what I have seen people saying that is not recommended.  This is why I have been looking for a native C# method of doing this.

Visual Basic
        For Each file In files
            DoFileStuff()
            Application.DoEvents()
        Next

This is useful if DoFileStuff() updates the UI. DoEvents() would then let go of control, so the UI could take a turn and refresh itself.

C#
        foreach (var file in files)
        {
            DoFileStuff();
            Thread.Sleep(0);
}
The thread goes to sleep and immediately wakes up ready to be scheduled for execution when it is its turn again.