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

  • SEARCH
  • Home
  • 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 566461
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T12:58:47+00:00 2026-05-13T12:58:47+00:00

In the following code sample I have an Async Calculator class. This is injected

  • 0

In the following code sample I have an Async Calculator class. This is injected with an ICalc, which will be a syncronous calculator. I use dependency injecting and mock the ICalc because this resembles my true scenario, though I guess the mocking isn’t really of relevance to the question. The AsyncCalc has a function which will call another function asynchronously – taking a callback as parameter. And when the async function call finishes the callback will be triggered with the result.

Now I want to test my asynchronous function – checking that the callback is triggered with the expected parameter. This code seems to work. However, I feel like it might blow up at any time – and my concern is race condition of the callback to finish before the function ends and the test is terminated – as this will be run in a separate thread.

My question now is if I’m on the right track unit testing the async function, or if anyone can help me get on the right track..? What would feel better is if I could ensure that the callback is triggered right away – and preferably on the same thread I guess? Can/Should it be done?

public interface ICalc
{
    int AddNumbers(int a, int b);
}

public class AsyncCalc
{
    private readonly ICalc _calc;
    public delegate void ResultProcessor(int result);
    public delegate int AddNumbersAsyncCaller(int a, int b);

    public AsyncCalc(ICalc calc)
    {
        _calc = calc; 
    }

    public void AddNumbers(int a, int b, ResultProcessor resultProcessor)
    {
        var caller = new AddNumbersAsyncCaller(_calc.AddNumbers);
        caller.BeginInvoke(a, b, new AsyncCallback(AddNumbersCallbackMethod), resultProcessor);
    }

    public void AddNumbersCallbackMethod(IAsyncResult ar)
    {
        var result = (AsyncResult)ar;
        var caller = (AddNumbersAsyncCaller)result.AsyncDelegate;
        var resultFromAdd = caller.EndInvoke(ar);

        var resultProcessor = ar.AsyncState as ResultProcessor;
        if (resultProcessor == null) return;

        resultProcessor(resultFromAdd);
    }             
}

[Test]
public void TestingAsyncCalc()
{
    var mocks = new MockRepository();
    var fakeCalc = mocks.DynamicMock<ICalc>();

    using (mocks.Record())
    {
        fakeCalc.AddNumbers(1, 2);
        LastCall.Return(3);
    }

    var asyncCalc = new AsyncCalc(fakeCalc);
    asyncCalc.AddNumbers(1, 2, TestResultProcessor);
}

public void TestResultProcessor(int result)
{
    Assert.AreEqual(3, result);
}
  • 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-13T12:58:47+00:00Added an answer on May 13, 2026 at 12:58 pm

    You could use a ManualResetEvent to synchronize your threads.

    In the following example, the test thread will block on the call to completion.WaitOne().
    The callback for the async calculation stores the result and then signals the event by calling completion.Set().

    [Test]
    public void TestingAsyncCalc()
    {
        var mocks = new MockRepository();
        var fakeCalc = mocks.DynamicMock<ICalc>();
    
        using (mocks.Record())
        {
            fakeCalc.AddNumbers(1, 2);
            LastCall.Return(3);
        }
    
        var asyncCalc = new AsyncCalc(fakeCalc);
    
        var completion = new ManualResetEvent(false);
        int result = 0;
        asyncCalc.AddNumbers(1, 2, r => { result = r; completion.Set(); });
        completion.WaitOne();
    
        Assert.AreEqual(3, calcResult);
    }
    
    // ** USING AN ANONYMOUS METHOD INSTEAD
    // public void TestResultProcessor(int result)
    // {
    //     Assert.AreEqual(3, result);
    // }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following sample code and noticed that if I attempt to use
I have the following sample code which doesn't seem to want to run. import
I have the following code sample, which produces an error with the included constant
I have the following code sample to illustrate my point. When I load this
Lets say we have following sample code in C#: class BaseClass { public virtual
I have the following code sample: class A { public: A(int a):AA(a) {}; int
I have the following code sample that im trying to wrap my head around
I have the following code sample: float val = 16777216.0F; var badResult = Convert.ToDecimal(val);
I have a Dictionary bound to DataGridView by using following sample code. DataGridView bound
I am new to Emacs, and I have the following code as a sample.

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.