Synchronous

All these examples will run on the main Excel thread.


Example 1

To run these examples, create a project similar to the Getting Started project and replace the "udf_" function with the ones below.
This function takes a text argument and returns a string concatenation.
This function will not update when you press F9.

public static string udf_SOMETEXT(string sArgument1) 
{
   return "text: " + aArgument1;
}

Example 2

This function will return tomorrows date.
This function will not update when you press F9.

public static DateTime udf_TOMORROW() 
{
   return DateTime.Today.AddDays(1);
}

Example 3

This function will lock the Excel session and will take a few seconds to run while it is calculating.
This function will not update when you press F9.

public static string udf_LOOP() 
{
   string sText = "";
   for (int icount = 1; icount <= 100000; icount++)
   {
      sText = sText + "a";
   }
   return "some text";
}

Example 4 - Not Thread Safe

This function will lock the Excel session and will only use ONE calculation thread.
This function is not thread safe.
This function will not update when you press F9.

public static object udf_LOOPTIMES(object arg) 
{
   DateTime start = DateTime.Now;
   string sText = "";
   for (int icount = 1; icount <= 50000; icount++)
   {
      sText = sText + "a";
   }

   DateTime end = DateTime.Now;
   return start + " - " + (end - start).TotalMilliseconds;
}

Example 5 - Thread Safe

This function will lock the Excel session and can use ALL the available calculation threads.
This is the same function, but this time it is declared as being thread safe.
This function will not update when you press F9.

[ExcelDna.Integration.ExcelFunction(IsExceptionSafe=true, 
                                    IsMacroType=false,
                                    IsThreadSafe=true)]
public static object udf_LOOPTIMES_TS(object arg)
{
   DateTime start = DateTime.Now;
   string sText = "";
   for (int icount = 1; icount <= 50000; icount++)
   {
      sText = sText + "a";
   }

   DateTime end = DateTime.Now;
   return start + " - " + (end - start).TotalMilliseconds;
}

Calculation Times

Create a new Blank workbook.
Enter the formula "=udf_LOOPTIMES()" into cell "B2".
Enter the formula "=udf_LOOPTIMES_TS()" into cell "D2".
Drag these formulas down to row 11.
SS



© 2022 Better Solutions Limited. All Rights Reserved. © 2022 Better Solutions Limited TopPrevNext