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 8123531
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T06:12:36+00:00 2026-06-06T06:12:36+00:00

I want to make a WCF timer service where clients can register in order

  • 0

I want to make a WCF timer service where clients can register in order to get called back from the service after a certain time has passed. The problem is that the client doesn’t get called back. No Exception is thrown.

The callback interface is:

[ServiceContract]
public interface ITimerCallbackTarget
{
  [OperationContract(IsOneWay = true)]
  void OnTimeElapsed(int someInfo);
}

The service looks like:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,
  ConcurrencyMode = ConcurrencyMode.Single)]  
public class TimerService : ITimerService
   private readonly Timer _timer = new Timer(2000); //System.Timers.Timer

   public void Subscribe()
   {
     ITimerCallbackTarget listener = 
       OperationContext.Current.GetCallbackChannel<ITimerCallbackTarget>();

     _timer.Elapsed += (p1, p2) =>
     {
       listener.OnTimeElapsed(999);
      };
     _timer.Start();
   }

The callback method used by the client is:

private class TimerCallbackTarget : ITimerCallbackTarget
{
  public void OnTimeElapsed(int someInfo)
  {
    Console.WriteLine(someInfo);
  }
}

The client registers like this:

private static void TestTimerService()
{
  InstanceContext callbackInstance = new InstanceContext(new TimerCallbackTarget());

  using (DuplexChannelFactory<ITimerService> dcf =
    new DuplexChannelFactory<ITimerService>(callbackInstance,  
      "TimerService_SecureTcpEndpoint"))
  {
    ITimerService timerProxy = dcf.CreateChannel();

    timerProxy.Subscribe();        
  }
}

If I use a different thread at the subscribe method without Timer it works:

  ThreadPool.QueueUserWorkItem(p =>
  {
    listener.OnTimeElapsed(999);
  });

It even works with the Timer (for three seconds) if I put a Thread.Sleep(3000) at the end of the subscribe method so my guess is that maybe the channel to the callback-object gets closed after the subscribe method is finished. Using a class-scope variable for the callback object retrieved with OperationContext.Current.GetCallbackChannel(); instead of the method-scope variable didn’t help.

Previously i tried creating new Threads in the elapsed event handler of the Timer of the timer service to make it faster. An ObjectDisposedException was thrown with the message: “Cannot access a disposed object. Object name: ‘System.ServiceModel.Channels.ServiceChannel”. I then tried to simplify my service and found that even using only the Timer causes problems as described but I guess the exception indicates that somewhere the connection to the client’s callback object is lost. It’s strange that there is no excepiton if I don’t make new threads in the Timer thread. The callback method just isn’t called.

  • 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-06-06T06:12:37+00:00Added an answer on June 6, 2026 at 6:12 am

    In a duplex binding the lifetime of the two channels are linked. If the channel to the TimerService closes, then the callback channel to the CallbackTarget closes too. If you try to use a channel that was closed, you can get an ObjectDisposedExcpetion. In your case this is bad, because you don’t want to keep the Subscribe() channel open just to receive OnTimeElasped() calls… and I’m assuming you want to subscribe for an infinitely long time.

    A duplex channel is trying to make your life easier, but doesn’t fit your needs. Behind the scenes a duplex channel is actually creating a second WCF service host for the CallbackTarget. If you create the client’s service host manually to receive callbacks, then you can manage its lifetime independently of the Subscribe() channel.

    Below is a fully functional command line program that demonstrates the idea:

    1. Create a TimerService
    2. Create a TimerClient to receive notificatioins
    3. Pass the TimerClient’s endpoint address to the TimerService as a part of the subscribe call
    4. TimerService uses the address it got from Subscribe() to send notifications to the TimerClient.

    Note that no channel is left open longer than needed to make a single call.

    Standard disclaimer: This is intended to show how to create “duplex like” behavior. There’s a lack of error handling and other short cuts.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ServiceModel;
    using System.Timers;
    using System.ServiceModel.Description;
    
    namespace WcfConsoleApplication
    {
        [ServiceContract]
        public interface ITimerCallbackTarget
        {
            [OperationContract(IsOneWay = true)]
            void OnTimeElapsed(int someInfo);
        } 
    
        [ServiceContract]
        public interface ITimerService
        {
            [OperationContract(IsOneWay = true)]
            void Subscribe(string address);
        }
    
    
        [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,
                         ConcurrencyMode = ConcurrencyMode.Single)]
        public class TimerService : ITimerService
        {
            private readonly Timer _timer = new Timer(2000);
            private ChannelFactory<ITimerCallbackTarget> _channelFac;
            private int _dataToSend = 99;
    
            public void Subscribe(string address)
            {
                // note: You can also load a configured endpoint by name from app.config here,
                //       and still change the address at runtime in code.
                _channelFac = new ChannelFactory<ITimerCallbackTarget>(new BasicHttpBinding(), address);
    
                _timer.Elapsed += (p1, p2) =>
                {
                    ITimerCallbackTarget callback = _channelFac.CreateChannel();
                    callback.OnTimeElapsed(_dataToSend++);
    
                    ((ICommunicationObject)callback).Close();
    
                    // By not keeping the channel open any longer than needed to make a single call
                    // there's no risk of timeouts, disposed objects, etc.
                    // Caching the channel factory is not required, but gives a measurable performance gain.
                };
                _timer.Start();
            }
        }
    
        [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,
                         ConcurrencyMode = ConcurrencyMode.Single)]
        public class TimerClient : ITimerCallbackTarget
        {
            public void OnTimeElapsed(int someInfo)
            {
                Console.WriteLine("Got Info: " + someInfo);
            }
        }
    
    
        class Program
        {
            static void Main(string[] args)
            {
    
                ServiceHost hostTimerService = new ServiceHost(typeof(TimerService), new Uri("http://localhost:8080/TimerService"));
                ServiceHost hostTimerClient = new ServiceHost(typeof(TimerClient), new Uri("http://localhost:8080/TimerClient"));
                ChannelFactory<ITimerService> proxyFactory = null;
    
                try
                {
                    // start the services
                    hostTimerService.Open();
                    hostTimerClient.Open();
    
                    // subscribe to ITimerService
                    proxyFactory = new ChannelFactory<ITimerService>(new BasicHttpBinding(), "http://localhost:8080/TimerService");
                    ITimerService timerService = proxyFactory.CreateChannel();
                    timerService.Subscribe("http://localhost:8080/TimerClient");
                    ((ICommunicationObject)timerService).Close();
    
                    // wait for call backs...
                    Console.WriteLine("Wait for Elapsed updates. Press enter to exit.");
                    Console.ReadLine();
                }
                finally
                {
                    hostTimerService.Close();
                    hostTimerClient.Close();
                    proxyFactory.Close();
                }
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to know whether unhandled exception will make WCF service crash. I have
I built a WCF service which produces JSON. I want to make an external
I want make a bash script which returns the position of an element from
I want make interactive application where user launches it and can do various task
I am trying to make a WCF REST method entirely asynchronous (I don't want
I've got a WCF service and want to connect to it using a TCP
How to initialize class in WCF? Suppose I just want to make a sum
Heres the background -- I want to self-host a WCF service implementing netTcpBinding and
I have a WCF service which is workng fine but I now want to
I am implementing a WCF service (Contract A) that will eventually make calls to

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.