I selected a solved problem to easily check the output.
“Perfect” numbers are the sum of all numbers that divide them without a remainder, except the “perfect” number itself, but including 1.
The “perfect” numbers are all known up to 10^300 or thereabouts. All known “perfect” numbers are even, and it is conjectured, without a proof at this time, that all such numbers are even.
Euclid developed an algorithm for calculating perfect numbers based on primes which was confirmed and polished by Euler, but I’m sick of prime numbers. I decided to write a C Sharp program that would determine perfecthood reasonably efficiently, and as it turned out, I needed to tune the Windows application running the program for multiple threads. In the latter activity I discovered a better way to handle threading inside traditional Windows forms.
It seemed to make sense to limit the determination of remainderless quotients to the square root of each number as we do in determining prime numbers, because for each n less than or equal to the square root of the candidate number C which divides C, we can get m such that n * m == C at the same time we determine whether its modulus is zero.
It would be elegant, of course, to call a fast divide which returns the quotient as a method value and the remainder by reference (or vice-versa): but I decided not to spend time on this.
Instead, I get reasonable performance by summing all n less than/equal to sqrt(C), therefore it is efficient to grab it when I take n.
I iterate starting above 2 and use shifting to determine whether the candidate is an even number, and add one (which always divides) when testing the sum against the candidate.
This has rounded up all the usual suspects:

If you let it run for a while (or change the source code to start at 33550336 or 137438691328) it displays 33,550,336, or 137,438,691,328. If you change the source code to start at the next number, 2305843008139952128, the application seems to run “forever”.
The further perfect numbers exceed the precision of a Long number (2^64-1) so there’s no point in trying to calculate them with this software. Basically, what we have is a marvelously useless tool which you can run to confirm that there are no odd perfect numbers less than 2^64, because Euclid-Euler calculates even perfect numbers only. But as an example of good C# code IMO, and, as we’ll see below, threading in forms, it might be of interest.
As to threading in forms, then: we know that Windows Forms are not thread safe. The Microsoft C# 2008 documentation recommends a clumsy use of Invoke inside extra form threads (such as the thread in which I calculate perfect numbers) to send all interactions, from the worker thread, back to the main form thread.
I realized that the only elegant way of using Invoke is to wrap it in a little Invoke manager with a dispatching enumerator, and that this could handle the final construction of an array of object arguments.
Ideally, all code in a modern Form would always use this form invoke manager (named formInvoke() here) so that at any time during software maintenance, the software maintainer would not have to worry about what thread was executing code being studied or changed. This is because Invoke simply does the form task directly when it is in the main thread.
However, it is typical, in legacy systems to which advanced features (such as multiple threads) are tacked-on, for programmers to handle new requirements that result from the new “power” by code snippets, taken from a magazine or a workmate sufficiently fat and sufficiently bearded to have a reputation as a technical guru.
(Damn right I’m angry at the lack of craft in American programming: the gloves are off, since the “credit crisis” is in large measure a consequence of sloppy programming.)
I prefer to create a new environment and a new abstraction, whence formInvoke.
Beyond this, I hesitate to tread into extra precision calculations, written in Intel assembler.
Here is the code. I wrote it without any comments although I prefer comments simply to get it done a bit faster. The actual listing as formatted by the code tag loses indentation so the copyable code listing is preceded by an image of the code that calculates perfect numbers to show the overall style.
You should be able to paste the copyable code into a Windows form code window under modern C Sharp enterprise/express, and get results.

Oh and by the way. The careful formatting of the above and its use of Hungarian notation used to be a Good Thing. Today, it galvanizes programming thugs who as practical men without illusions have inchoately theorized the strange notion that all such touches indicate, not competence, but its reverse.
Cf. that usenet intellectual slum comp.programming for an example. These are the men Adorno meant in 1948. Afraid that the secret contour of their weakness will be exposed they find it instead in anything, whether English or code, in which any effort has been expended.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace perfectNumbers
{
public partial class perfectNumbers : Form
{
Label LBLoutput;
Label LBLstatus;
Button CMDstop;
System.Threading.Thread OBJcalculationThread;
string STRtext;
CheckBox CHKstatus;
public perfectNumbers()
{
InitializeComponent();
}
private void chkStatus_CheckedChanged
(object objSender,
EventArgs objEventArgs)
{
LBLstatus.Visible = CHKstatus.Checked;
LBLstatus.Refresh();
}
private void cmdClose_Click(object objSender,
EventArgs objEventArgs)
{
closer();
}
private void cmdCalculatePerfectNumbers_Click
(object objSender,
EventArgs objEventArgs)
{
(OBJcalculationThread =
new
System.Threading.Thread
(new System.Threading.ThreadStart
(calculatePerfectNumbers))).Start();
}
private void cmdStop_Click(object objSender,
EventArgs objEventArgs)
{
OBJcalculationThread.Abort();
while (OBJcalculationThread.ThreadState
!=
System.Threading.ThreadState.Stopped) { }
changeFormState(ENUformState.waiting);
}
private void perfectNumbers_Load(object objSender,
EventArgs objEventArgs)
{
Text = Application.ProductName;
STRtext = Text;
if (!customizeForm()) closer();
state2Label(ENUcalculationState.quiescent);
}
private void calculatePerfectNumbers()
{
changeFormState(ENUformState.running);
long lngIndex1 = 0;
long lngIndex2 = 0;
long lngSum = 0;
string strSep = "";
string strTextStart = "Calculating perfect numbers";
formInvoke(this, ENUformInvokeOp.setText, strTextStart);
for (lngIndex1 = 6;
lngIndex1 2;
lngIndex2--)
{
if (lngIndex1 % lngIndex2 == 0)
{
lngSum += lngIndex2;
lngSum += (long)(lngIndex1 / lngIndex2);
}
}
state2Label(ENUcalculationState.iteratingOverCandidates);
if (((lngIndex2 = (lngIndex1 >> 1)) << 1)
==
lngIndex1)
{
lngSum += 2;
lngSum += lngIndex2;
}
if (lngSum + 1 == lngIndex1)
{
formInvoke(LBLoutput,
ENUformInvokeOp.setText,
LBLoutput.Text +
strSep +
lngIndex1.ToString());
formInvoke(this, ENUformInvokeOp.refresh);
strSep = ", ";
}
if (lngIndex1 % 100 == 0)
{
formInvoke(this,
ENUformInvokeOp.setText,
strTextStart + " at " +
lngIndex1.ToString());
}
}
changeFormState(ENUformState.waiting);
}
private enum ENUformState { running, waiting }
private void changeFormState(ENUformState enuNewState)
{
switch (enuNewState)
{
case ENUformState.running:
{
formInvoke(this,
ENUformInvokeOp.enableDisableControlCollection,
false);
formInvoke(CMDstop,
ENUformInvokeOp.enableDisableControl,
true);
formInvoke(LBLoutput,
ENUformInvokeOp.enableDisableControl,
true);
formInvoke(CHKstatus,
ENUformInvokeOp.enableDisableControl,
true);
formInvoke(LBLoutput,
ENUformInvokeOp.setText,
"");
break;
}
case ENUformState.waiting:
{
formInvoke(this,
ENUformInvokeOp.enableDisableControlCollection,
true);
formInvoke(CMDstop,
ENUformInvokeOp.enableDisableControl,
false);
formInvoke(this,
ENUformInvokeOp.setText,
STRtext);
state2Label(ENUcalculationState.quiescent);
break;
}
default:
throw new Exception("Invalid form state");
}
}
private void closer()
{
Application.Exit();
}
private bool customizeForm()
{
ControlBox = false;
Text = Application.ProductName;
FormBorderStyle = FormBorderStyle.Fixed3D;
Width = Width << 1;
CenterToScreen();
int intGrid = windowsUtilities.windowsUtilities.Grid;
Button cmdNew =
windowsUtilities.windowsUtilities.mkButton
("Close",
ClientSize.Width
-
intGrid
-
windowsUtilities.windowsUtilities.defaultButtonWidth(),
ClientSize.Height
-
intGrid
-
windowsUtilities.windowsUtilities.defaultButtonHeight());
cmdNew.Click += cmdClose_Click;
Controls.Add(cmdNew);
Button cmdClose = cmdNew;
cmdNew =
windowsUtilities.windowsUtilities.mkButton
("Calculate perfect numbers",
intGrid,
cmdNew.Top,
cmdNew.Width << 1);
cmdNew.Click += cmdCalculatePerfectNumbers_Click;
Controls.Add(cmdNew);
cmdNew =
windowsUtilities.windowsUtilities.mkButton
("Stop",
cmdNew.Right + intGrid,
cmdNew.Top,
cmdClose.Width);
cmdNew.Click += cmdStop_Click;
Controls.Add(cmdNew);
cmdNew.Enabled = false;
CMDstop = cmdNew;
int intGrid2 = intGrid << 1;
LBLoutput =
windowsUtilities.windowsUtilities.mkLabel
("",
intGrid,
intGrid,
ClientSize.Width - intGrid2,
ClientSize.Height
-
(intGrid2 + intGrid)
-
cmdNew.Height);
LBLoutput.BorderStyle = BorderStyle.Fixed3D;
LBLoutput.Font = new Font(FontFamily.GenericMonospace, 10);
Controls.Add(LBLoutput);
CHKstatus =
windowsUtilities.windowsUtilities.mkCheckBox
("Show status",
CMDstop.Right + intGrid,
CMDstop.Top);
CHKstatus.CheckedChanged += chkStatus_CheckedChanged;
Controls.Add(CHKstatus);
LBLstatus =
windowsUtilities.windowsUtilities.mkLabel
("",
CHKstatus.Right + intGrid,
CMDstop.Top,
windowsUtilities.windowsUtilities.defaultLabelWidth(),
CMDstop.Height);
LBLstatus.BorderStyle = BorderStyle.Fixed3D;
LBLstatus.Font = new Font(FontFamily.GenericMonospace, 10);
Controls.Add(LBLstatus);
CHKstatus.Checked = true;
return true;
}
private enum ENUformInvokeOp
{
enableDisableControl,
enableDisableControlCollection,
queryEnabled,
queryVisible,
refresh,
setBGFGcolor,
setText
}
delegate object DELformInvoke
(Control ctlControl,
ENUformInvokeOp enuOp,
params object[] objOperands);
private object formInvoke(Control ctlControl,
ENUformInvokeOp enuOp)
{
object[] objDummy = null;
try
{
objDummy = new object[1];
objDummy[0] = null;
}
catch (Exception objException)
{
throw new Exception
("Cannot create dummy operand array",
objException);
}
return formInvoke(ctlControl, enuOp, objDummy);
}
private object formInvoke
(Control ctlControl,
ENUformInvokeOp enuOp,
params object[] objOperandsParams)
{
if (ctlControl.InvokeRequired)
{
object[] objInvokeOperandsBase = null;
object[] objInvokeOperandsParams = null;
try
{
objInvokeOperandsBase = new object[3];
objInvokeOperandsParams =
new object
[objOperandsParams.GetUpperBound(0) + 1];
}
catch (Exception objException)
{
throw new Exception("Cannot create operand arrays",
objException);
}
int intIndex1 = 0;
foreach (object objOperand in objOperandsParams)
objInvokeOperandsParams[intIndex1++] = objOperand;
objInvokeOperandsBase[0] = ctlControl;
objInvokeOperandsBase[1] = enuOp;
objInvokeOperandsBase[2] = objInvokeOperandsParams;
return ctlControl.Invoke(new DELformInvoke(formInvoke),
objInvokeOperandsBase);
}
else
{
try
{
lock (ctlControl)
{
switch (enuOp)
{
case ENUformInvokeOp.enableDisableControl:
{
ctlControl.Enabled =
(bool)objOperandsParams[0];
return true;
}
case ENUformInvokeOp.enableDisableControlCollection:
{
int intIndex1 = 0;
for (intIndex1 = 0;
intIndex1 < ctlControl.Controls.Count;
intIndex1++)
ctlControl.Controls[intIndex1].Enabled =
(bool)objOperandsParams[0];
return true;
}
case ENUformInvokeOp.queryEnabled:
{
return ctlControl.Enabled;
}
case ENUformInvokeOp.queryVisible:
{
return ctlControl.Visible;
}
case ENUformInvokeOp.refresh:
{
ctlControl.Refresh();
return true;
}
case ENUformInvokeOp.setText:
{
ctlControl.Text =
(string)objOperandsParams[0];
return true;
}
case ENUformInvokeOp.setBGFGcolor:
{
ctlControl.BackColor =
(Color)objOperandsParams[0];
ctlControl.ForeColor =
(Color)objOperandsParams[1];
return true;
}
default:
throw new Exception
("Invalid op " +
enuOp.ToString());
}
}
}
catch (Exception objException)
{
throw new Exception("Error in Invoked op",
objException);
}
}
}
private enum ENUcalculationState
{
iteratingOverCandidates,
dividingCandidate,
quiescent
}
private const string CALCULATIONSTATE_ITERATINGOVERCANDIDATES =
"Iterating over candidates";
private const string CALCULATIONSTATE_SEARCHING =
"Searching for divisors";
private const string CALCULATIONSTATE_QUIESCENT =
"";
private void state2Label(ENUcalculationState enuState)
{
if (!(bool)
formInvoke(LBLstatus,
ENUformInvokeOp.queryVisible)) return;
Color objBG = Color.White;
Color objFG = Color.Black;
state2ColorScheme(enuState, ref objBG, ref objFG);
formInvoke(LBLstatus,
ENUformInvokeOp.setBGFGcolor,
objBG, objFG);
formInvoke(LBLstatus,
ENUformInvokeOp.setText,
state2String(enuState));
formInvoke(this, ENUformInvokeOp.refresh);
}
private static void state2ColorScheme
(ENUcalculationState enuState,
ref Color objBG,
ref Color objFG)
{
switch (enuState)
{
case ENUcalculationState.iteratingOverCandidates:
{
objBG = Color.Yellow; objFG = Color.Black;
break;
}
case ENUcalculationState.dividingCandidate:
{
objBG = Color.Red; objFG = Color.White;
break;
}
case ENUcalculationState.quiescent:
{
objBG = Color.White; objFG = Color.Black;
break;
}
default:
throw new Exception("Invalid state");
}
}
private static string state2String
(ENUcalculationState enuState)
{
switch (enuState)
{
case ENUcalculationState.iteratingOverCandidates:
return CALCULATIONSTATE_ITERATINGOVERCANDIDATES;
case ENUcalculationState.dividingCandidate:
return CALCULATIONSTATE_SEARCHING;
case ENUcalculationState.quiescent:
return CALCULATIONSTATE_QUIESCENT;
default: return "Unknown state";
}
}
}
}