简体   繁体   中英

C# Async Server action every second

I've successfully created a simple server and client application in C# that communicate asynchronously between the server and multiple clients, i used the following Microsoft Docs to create it:

https://docs.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-server-socket-example

https://docs.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-client-socket-example

They are both working fine, but my question is, i want to execute an action every second on the server and i don't know the best way to go about it. Should i use something like the Timer class to do it? Is using a Timer interfere in any way with the calls that the server is receiving from the clients?

Yes a timer is a good way to it.

I have something similar for a Blazor component called a Sprite, where I perform a movement of an image everytime the timer event goes off.

In my case my subscriber is an interface, ISpriteSubscriber:

namespace DataJuggler.Blazor.Components.Interfaces
{

    #region interface ISpriteSubscriber
    /// <summary>
    /// This interface is used by the AnimationManager to notifiy callers that a refresh occurred.
    /// </summary>
    public interface ISpriteSubscriber
    {

        #region Methods

            #region Refresh()
            /// <summary>
            /// This method will call StateHasChanged to refresh the UI
            /// </summary>
            void Refresh();
            #endregion

            #region Register(Sprite sprite)
            /// <summary>
            /// This method is called by the Sprite to a subscriber so it can register with the subscriber, and 
            /// receiver events after that.
            /// </summary>
            void Register(Sprite sprite);

        #endregion

        #endregion

        #region Properties

            #region ProgressBar
            /// <summary>
            /// This is used so the ProgressBar is stored and available to the Subscriber after Registering
            /// </summary>
            ProgressBar ProgressBar { get; set; }
            #endregion

        #endregion

    }
    #endregion

}

public ISpriteSubscriber Subscriber { get; set; }

In my Start event, I create the Timer:

public void Start()
{
    this.Timer = new Timer();
    this.Timer.Interval = this.interval;
    this.Timer.Elapsed += Timer_Elapsed;
    this.Timer.Start();
}

private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
    // if a subscriber (returns true if Subscriber != null)
    if (HasSubscriber)
    {
        // Notify Subscriber
        Subscriber.Refresh();
    }
}

public void Refresh()
{
    // do your actions here
}

public void Register(Sprite sprite)
{
    // If the sprite object exists
    if (NullHelper.Exists(sprite))
    {
        // if this is the RedCar
        if (sprite.Name == "RedCar")
        {
            // Set the RedCar
            RedCar = sprite;
        }
        else 
        {
            // Set the WhiteCar
            WhiteCar = sprite;
        }
    }
}

The Refresh event is where I move an image (by random numbers in my example).

One tip When using a timer that goes off as often as you have it, I usually put something like a NotificationInProgress flag or something in case one operation takes longer than a second.

Maybe in your use case it is ok to have multiple messages, but sometimes you need to wait on one to finish before completing the next.

public bool NotificationInProgress { get; set; }

Then before you notify a Subscriber I test

if (!NotificationInProgress)
{
    // send your message.
}

If you want to see an open source Blazor sample project where I demonstrate simple animations that this code came from, it is here:

https://github.com/DataJuggler/DataJuggler.Blazor.Components

在此处输入图片说明

Maybe it will give you some ideas on how to arrange your project.

I would suggest using some form of Thread.Sleep or calling await on a method with a Task.Delay. See an example here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM