Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7278197
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T22:50:31+00:00 2026-05-28T22:50:31+00:00

I am interested in timing my function calls to database + other functions to

  • 0

I am interested in timing my function calls to database + other functions to build some metrics for my application’s performance. I used Stopwatch and a metrics object, but it doesn’t seem to consistently give correct values. Sometimes the elapsed time for calling a function is exactly the same for all the calls which is unrealistic…

I have discovered that the reason for the problem is due to the Metrics object properties values. The values of one Metrics object get overwritten when other instances of the Metrics generated by other threads are assigned values. It seems like the properties values are per reference although a new instance is created by each thread.

What’s the best approach to achieve uniqueness in an object shared by multiple threads?

Code below:

private Metrics Metrics;
private Stopwatch Stopwatch;
private int DegreeOfParallelism { get { return Convert.ToInt32(ConfigurationManager.AppSettings["DegreeOfParallelism"].ToString()); } }

var lOptions = new ParallelOptions() { MaxDegreeOfParallelism = DegreeOfParallelism };
Parallel.ForEach(RequestBag, lOptions, (lItem, loopState) =>
{
    if (!string.IsNullOrEmpty(lItem.XmlRequest))
    {
        try
        {
            Metrics = new Metrics();
            Stopwatch = new Stopwatch();
            Stopwatch.Start();
            ObjRef = new Object();
            lItem.XmlRequest = ObjRef.GetDecision(Username, Password);
            Stopwatch.Stop();
            Metrics.ElapsedTime = string.Format("{0:0.00}", Stopwatch.Elapsed.TotalSeconds);

            Stopwatch.Restart();
            if (!string.IsNullOrEmpty(DBConnectionString))
            {
                DataAccess = new DataAccess2(DBConnectionString);
                DataAccess.WriteToDB(lItem.XmlRequest);  
            }
            Stopwatch.Stop();
            Metrics.DbFuncCallTime = string.Format("{0:0.00}", Stopwatch.Elapsed.TotalSeconds); 
        }
        catch (Exception pEx)
        { 
            KeepLog(pEx);
            Metrics.HasFailed = true;
        }
        finally
        {
            ProcessedIdsBag.Add(lItem.OrderId);
            Metrics.ProcessedOrderId = lItem.OrderId;
            Metrics.DegreeOfParallelism = DegreeOfParallelism;
            Metrics.TotalNumOfOrders = NumberOfOrders;
            Metrics.TotalNumOfOrdersProcessed = ProcessedIdsBag.Count;
            pBackgroundWorker.ReportProgress(Metrics.GetProgressPercentage(NumberOfOrders, ProcessedIdsBag.Count), Metrics);

            RequestBag.TryTake(out lItem);
        }
    }
});

Any help will be very much appreciated.
Thanks,
R

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T22:50:32+00:00Added an answer on May 28, 2026 at 10:50 pm

    What it seems that you want to do is create a metrics object for each iteration, and then aggregate them at the end:

    private ConcurrentBag<Metrics> allMetrics = new ConcurrentBag<Metrics>();
    private int DegreeOfParallelism { get { return Convert.ToInt32(ConfigurationManager.AppSettings["DegreeOfParallelism"].ToString()); } }
    
    var lOptions = new ParallelOptions() { MaxDegreeOfParallelism = DegreeOfParallelism };
    Parallel.ForEach(RequestBag, lOptions, (lItem, loopState) =>
    {
        if (!string.IsNullOrEmpty(lItem.XmlRequest))
        {
            try
            {
                var Metrics = new Metrics();
                var Stopwatch = new Stopwatch();
                Stopwatch.Start();
                ObjRef = new Object();
                lItem.XmlRequest = ObjRef.GetDecision(Username, Password);
                Stopwatch.Stop();
                Metrics.ElapsedTime = string.Format("{0:0.00}", Stopwatch.Elapsed.TotalSeconds);
    
                Stopwatch.Restart();
                if (!string.IsNullOrEmpty(DBConnectionString))
                {
                    DataAccess = new DataAccess2(DBConnectionString);
                    DataAccess.WriteToDB(lItem.XmlRequest);  
                }
                Stopwatch.Stop();
                Metrics.DbFuncCallTime = string.Format("{0:0.00}", Stopwatch.Elapsed.TotalSeconds); 
            }
            catch (Exception pEx)
            { 
                KeepLog(pEx);
                Metrics.HasFailed = true;
            }
            finally
            {
                ProcessedIdsBag.Add(lItem.OrderId);
                Metrics.ProcessedOrderId = lItem.OrderId;
                Metrics.DegreeOfParallelism = DegreeOfParallelism;
                Metrics.TotalNumOfOrders = NumberOfOrders;
                Metrics.TotalNumOfOrdersProcessed = ProcessedIdsBag.Count;
                pBackgroundWorker.ReportProgress(Metrics.GetProgressPercentage(NumberOfOrders, ProcessedIdsBag.Count), Metrics);
    
                RequestBag.TryTake(out lItem);
                allMetrics.add(Metrics);
            }
        }
    });
    
    // Aggregate everything in AllMetrics here
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Interested if anyone has used VSTS Database Edition extensively and, if so, which features
I'm interested in learning some (ideally) database agnostic ways of selecting the n th
I would like to add some automated performance test to my Objective-C application. (This
im interested how many api calls per second or per minute i can do
Although I'm specifically interested in web application information, I would also be somewhat curious
I'd be interested in some before-and-after c# examples, some non-idiomatic vs idiomatic examples. Non-c#
Interested in people's opinion. You have an application server running 3/4 services that do
I`m interested in using some MOSS dll's if my solution is deployed on MOSS.
im interested i just finished writing a program and one of the functions that
Interested in using Sphinx for my application. Planning to install their latest version which

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.