INCLUDE_DATA

 
»
S
I
D
E
B
A
R
«
aquisto cialis levitra svizzera tadalafil bestellen viagra prix acheter du viagra acquista levitra cialis sur internet citrate de sildenafil compro viagra levitra ricetta kamagra pharmaceuticals cialis vente libre cialis suisse levitra italia vente de cialis viagra suisse kamagra gel viagra quanto costa cialis 20 mg prix cialis 10mg viagra verkauf cialis moins cher viagra prezzo levitra kopen acheter tadalafil acheter kamagra tadalafil generico impuissance sexuelle cialis preco levitra donna viagra 100 mg comprar cialis generico comprar levitra cialis a vendre procurer du cialis generische cialis vardenafil generico vardenafil generika levitra sur internet generische viagra acheter cialis generique acquista viagra achat cialis viagra 100 mg cialis generico kamagra en france viagra ordonnance acheter viagra achat vardenafil pastilla levitra viagra cialis differenze impotenza sessuale venta viagra medicament cialis curare impotenza kamagra te koop achat cialis 20mg levitra pharmacie cialis receta acquisto viagra net cialis en ligne achat de viagra cialis generique acheter acheter du cialis cialis 20 mg vardenafil 10 mg viagra alternativo citrate de sildenafil cialis sin receta viagra kopen acheter cialis en pharmacie kamagra bestellen comprar viagra pela internet viagra prescrizione levitra donne vente cialis venta de sildenafil achete levitra acheter cialis france venta de levitra viagra kosten cialis marche pas comprar vardenafil disfunzione erettile rimedi vardenafil generique viagra recensioni cialis generico prezzo viagra versand cialis europe viagra venta libre impotenza rimedi cialis rezeptfrei acheter kamagra france levitra ohne rezept acquisto viagra in contrassegno prix de cialis cialis prescrizione viagra acquisto online achat viagra pildoras cialis kamagra generique cialis prezzo cialis inde cialis sur le net acheter cialis en espagne levitra ordonnance viagra naturel cialis 10 mg acquistare levitra procurer du viagra acquisto viagra senza ricetta viagra controindicazioni levitra 20 mg compra viagra impuissance erection acheter cialis pharmacie prezzi levitra viagra ohne rezept kamagra apcalis comprar viagra commander du cialis cialis ricetta medica sildenafil 50 mg sildenafil venta viagra italia pilule levitra sildenafil generico viagra prijs
Using Yield in C#
May 22nd, 2009 by Jason

The yield Statement

yield is an overlooked, yet powerful feature.

yield basics

yield places values into an IEnumerable object.
To further understand what yield does, here’s an example with trace statements between each yield statement:

//:SimpleYield.cs
using System;
using System.Collections.Generic;

class SimpleYield
{
static IEnumerable GetValues(){
Console.WriteLine("Returning 1");
yield return 1;
Console.WriteLine("Returning 2");
yield return 2;
Console.WriteLine("Returning 3");
yield return 3;
}
static void Main(){
//Iterate over YieldMethod's IEnumerable
foreach(int i in GetValues())
Console.WriteLine(i);
}
}/*Output:
Returning 1
1
Returning 2
2
Returning 3
3
*///:~

GetValues( )’s yield statements return hard-coded integer values. Main( ) iterates these values, printing each. Notice how GetValue( )’s trace statements interlace with Main( )’s.
A yield statement comes in two different forms, yield return and yield break. yield return places the evaluated expression as the current value of the IEnumerable. yield break marks the end of an iterator:

//:YieldBreak.cs
using System;
using System.Collections.Generic;

class YieldBreak{
static IEnumerable GetValues(){
Console.WriteLine("Returning 1");
yield return 1;
Console.WriteLine("Returning 2");
yield return 2;
Console.WriteLine("Breaking");
yield break;                //Break Here
Console.WriteLine("Returning 3");
yield return 3;
}
static void Main(){
foreach(int i in GetValues())
Console.WriteLine(i);
}
}/*Output:
Returning 1
1
Returning 2
2
Breaking
*///:~

yield break prevents remaining code from executing. It reports back to the foreach that there are no values remaining in the IEnumerable. C#’s compiler reports a warning about any unreachable code following yield break.
Exercise 1: Use Visual Studio’s debugger to step through (F11) SimpleYield.cs. Follow the code path as the foreach executes.
Exercise 2: Create a GetValue( ) method that returns a random number of integer values. Use yield return and yield break.

///: Exercise2.cs
using System;
using System.Collections.Generic;

class Exercise2{
public static IEnumerable GetValues(){
Random rand = new Random();
int current = 0;
while (true){
current = rand.Next(20);
if (current == 17)
yield break;
yield return current;
}
}

public static void Main(){
foreach (int i in GetValues()){
Console.WriteLine(i);
}
}
}
///:~

yield Benefits

One strong feature of yield is its ability to defer processing. It delays any calculation until absolutely necessary. Deferred processing makes more responsive programs. yield spreads wait time amongst all iterations by creating values only when necessary:

///: DeferredProcessingTime.cs
using System;
using System.Collections.Generic;
using System.Threading;

class DeferredProcessingTime{
public static IEnumerable CalculateAtOnce(){
int[] intArray = new int[10];
for (int i = 0; i < 10; i++){
Thread.Sleep(1000);
intArray[i] = i;
}
return intArray;
}
public static IEnumerable DeferredCalculate(){
for (int i = 0; i < 10; i++){
Thread.Sleep(1000);
yield return i;
}
}
public static void Main(){
Console.WriteLine("Calculate at once");
foreach (int i in CalculateAtOnce()) //Ten seconds before printing
Console.Write(i);
Console.WriteLine("\nUsing Yield");
foreach (int z in DeferredCalculate())
Console.Write(z); //One second between each write
}
}/*Output:
Calculate at once
0123456789
Using Yield
0123456789
*///:~

The above example emulates an algorithm that takes a long time to process by using Thread.Sleep( ) before adding each value.
Both foreachs over CalculateAtOnce( ) and DefferedCalculate( ) print the same results to the console. However the execution behavior is noticeably different. CalculateAtOnce( )’s foreach waits for 10 seconds and prints 0 through 9. DeferredCalculate( )’s foreach prints each value per second.
Another benefit of yield’s deferred processing is that it does not require a collection stored in memory. yield can iterate over a large set of data without consuming large amounts of memory. Take the following example. You iterate over a set of data with 10 million integer values. Without yield, the entire collection of values must be returned. With yield, each integer value is returned when requested.

///:DeferredProcessingMemory.cs
using System;
using System.Collections.Generic;
using System.Threading;

class DeferredProcessingMemory{
public static IEnumerable CalculateAtOnce(){
int[] intArray = new int[10000000];
for (int i = 0; i < 10000000; i++)
intArray[i] = i;
return intArray;
}
public static IEnumerable DeferredCalculate(){
for (int i = 0; i < 10000000; i++)
yield return i;
}
public static void Main(){
Console.WriteLine("Using Yield");
IEnumerable deferred = DeferredCalculate();
Console.ReadLine(); //Memory usage: ~2MB
Console.WriteLine("Calculating at once");
IEnumerable atOnce = CalculateAtOnce();
Console.ReadLine(); //Memory usage: ~40MB
}
}/*Output:
Using Yield

Calculating at once

*///:~

Start the Windows Task Manager (Ctrl+Shift+Esc) before running this example. Find your process, and notice the amount of memory usage from using DeferredCalculate( ). Press enter and see the drastic increase that CalculateAtOnce( ) makes; intArray’s 10 million in-memory values are the cause.
yield gives potential to handle data sets of any size without concern for memory limitations.
Exercise 3: Use yield to iterate over an infinite data set of random integers.

///:Exercise3.cs
using System;
using System.Collections.Generic;

class Exercise3{
public static Random rand = new Random();
public static IEnumerable GetValues(){
while(true)
yield return rand.Next();
}
public static void Main(){
foreach(int i in GetValues())
Console.WriteLine(i);
}
}
///:~

Under the Hood

Many C# keywords involve the generation of MSIL code, methods, or even classes. yield is no exception.
Red Gate’s .NET Reflector shows the generated C# from using the yield statement. The disassembled assembly of SimpleYield.cs contains an extra class implementing IEnumerable.

public class GeneratedClass : IEnumerable, IEnumerable,
IEnumerator, IEnumerator, IDisposable{
//...CUT...
public bool MoveNext(){
switch (this.state){
case 0:
this.state = -1;
Console.WriteLine("Returning 1");
this.current = 1;
this.state = 1;
return true;

case 1:
this.state = -1;
Console.WriteLine("Returning 2");
this.current = 2;
this.state = 2;
return true;

case 2:
this.state = -1;
Console.WriteLine("Returning 3");
this.current = 3;
this.state = 3;
return true;

case 3:
this.state = -1;
break;
}
return false;
}
//...CUT...
}

The compiler generates a switch statement to handle executing the code written in your original yielding method. Only one case statement is used for each time MoveNext( ) is called. This is how the deferred processing actually occurs.
GetValues( ) is also changed to use the GeneratedClass( ) in place of the original code.

private static IEnumerable GetValues(){
return new GeneratedClass(-2);
}

The -2 in the new GeneratedClass( ) call is used to set the initial state. The state’s value is changed when MoveNext( ) is called. Beginning each case, state is set to -1 to prevent further execution if an exception occurs. Just before a case returns, state is assigned the value of the next case.
Exercise 4: Write an implementation of yield’s generated code and execute a foreach over it.

//:Exercise4.cs
using System;
using System.Collections.Generic;
using System.Collections;

class Exercise4 : IEnumerable,IEnumerable,
IEnumerator,IEnumerator, IDisposable{
string current = "";
int state;
public IEnumerator GetEnumerator(){
return this;
}
IEnumerator IEnumerable.GetEnumerator(){
return GetEnumerator();
}
public string Current{
get { return current; }
}
public void Dispose(){}
object IEnumerator.Current{
get { return Current; }
}
public bool MoveNext(){
switch(state){
case 0:
state = -1;
current = "One";
state = 1;
return true;
case 1:
state = -1;
current = "Two";
state = 2;
return true;
case 2:
state = -3;
current = "Three";
state = 3;
return true;
}
return false;
}
public void Reset(){
throw new NotImplementedException();
}
public static void Main(){
foreach(string s in new Exercise4())
Console.WriteLine(s);
}
}/*Output:
One
Two
Three
*///:~
Blocks of Leadership
Dec 13th, 2008 by Jason

Last week I was given the opportunity to interview with a company I’ve held an internship with for the past three months. Sitting in a room across from four men, each scanning my resume, I was bombarded with questions about my past experience, thinking patterns, and technical abilities. One pattern that seemed to stand out amidst the inquiries was the leadership theme. Questions like “how would you handle a poorly performing teammate” or “what roles on projects have you had in the past” were frequent. With this single experience alone, a clear display of the importance of leadership abilities within the workplace of any company is shown. My own personal beliefs on the roles and responsibilities of a leader have grown throughout the FC301 class and have found five important steps in taking a leadership position.

The first building block is to work with what you have. Allocate what strengths and weaknesses that your team has and adjust accordingly. Whenever you are placed with a new group, situation, or even morale, a recalculation of this is vital. If your members primarily held a strength in roofing houses, you wouldn’t also take up wiring the electrical or pouring concrete for the driveway. Sure, it might be able to be accomplished, but with the time and training required to learn the new skills you could’ve put three more roofs on. Making an emphasis on what you’re good at is a must to stay afloat. When it comes to individual member of a team, the same rule applies. Don’t put your database architect on the user interface portion of a computer and expect the quality you get when they do back-end work. It just doesn’t make much sense.

Next, you need to organize the process that the team works with to produce output fast, yet reasonably. This theory came to me during my internship when we used the Agile SCRUM methodology for developing software. Now without getting too in depth on SCRUM, it’s based around having visible output every day and having a working product at the close of each two to four week “sprint.” Having short spans between each release of a project allows a team to frequently compare their direction with a customer’s vision. Because of this format, the greatest amount of loss is a single sprint’s worth the time. Another factor is to have the personnel responsible for a specific portion of a product estimate the amount of time to complete their part. This prevents you as a leader from blindly cracking a whip on those who have been working to their fullest potential and well as make more accurate release dates for your customers.

Knowing how to evaluate your options to take risks is a skill that requires a lot of prior experience. However, anyone new to making risky decisions should not use this as a reason to cower and always play it safe. It’s been said in many different ways in the past that those who have had the most success are the same people who have had the most failures. A good metaphor to this principle is the Microsoft Windows game of Minesweeper. Occasionally you are met with a situation where you are uncertain where a mine lies, but need to make a move so you don’t just fill the timer with “999.” There are essentially two options when you click on any square within the game; if the square is a mine then you lose and must start over. However, if the position is safe, you are provided with the positions of more mines. This is not so different from the real world. Risks have consequences and rewards, and the only way to learn to handle them is to experience them.

One must always remember the reason why you are working on a team. In most situations it is coming together to complete a task that all members hold some form of interest in. Keeping this in mind, you must understand that it is okay if everyone on the team is not always pleased. You are not on the team to be best friends, share personal secrets, and grow old together; you’re there to accomplish a task. This is where I find it appropriate to “tilt the scales” just a bit in your procedures towards finishing the objective of the team in place of attempting to make every member happy 24/7. If you fail to meet a deadline, you can be assured that no one will be happy.

Think about the last time you drove somewhere in your car, did you just go and start it up? Or did you pop the hood, check your fluids, your tires, and change your air filter? Most people I know would trust that those things would be okay on a day to day basis. This same Idea applies to working with a team. If you’re constantly checking them and not trusting that they’re okay then the team’s “car” won’t get anywhere. Not that knowing what your members are doing is a bad thing, but there’s no better way to degrade the performance of someone than to be watching and criticizing over someone’s shoulder. Often times, when someone is relaxed and has space to do things without worry of making a small slip up, they are the most productive.

Overall, leading a team is an important skill for anyone to have that works in a company with more than one employee. There is no set way for someone to be the best possible leader in all situations, but trying different methodologies, taking risks, and trusting your team are all ways towards finding your own optimal form. After studying about a different form of leadership within FC301 this quarter, I’ve definitely gained a stronger position on how I need to lead a team in the future.

»  Substance: WordPress   »  Style: Ahren Ahimsa Blog Flux Local - Utah
© Jason Staten 2009