简体   繁体   English

在方法处理C#时显示Timer

[英]Show Timer while method is processing C#

I want to display the time elapsing in seconds while a method is processing and returns its response. 我想显示方法正在处理并返回其响应的时间(以秒为单位)。 Probably it will be done with Tasks or Threads but i am not really able to achieve it. 可能将通过Tasks或Threads完成,但我实际上无法实现。 Any help would be appreciated. 任何帮助,将不胜感激。

Thanks. 谢谢。

public function()
{
    while(wait for getAllInformation() function is processing)
    {
        Console.Write("Elapsed time... "+ some timer which shows time in seconds);
    }
}

You should use Microsoft' Reactive Framework for this. 您应该为此使用Microsoft的Reactive Framework。 Then you can simply do this: 然后,您可以简单地执行以下操作:

public int GetAllInformationWithTimer()
{
    using (Observable.Interval(TimeSpan.FromSeconds(1.0))
        .Subscribe(x => 
            Console.WriteLine("Elapsed Time: {0} seconds", x + 1)))
    {
        return GetAllInformation();
    }   
}

Just NuGet "System.Reactive" to get the library you need. 只需NuGet“ System.Reactive”即可获取所需的库。

Something like that: 像这样:

public async Task MyMehod()
{
            Task<IEnumerable<int>> infoGetTask = GetAllInformation();

            Stopwatch stopwatch = Stopwatch.StartNew();

            while (!infoGetTask.IsCompleted)
            {
                Console.Write($"Elapsed time... {Math.Round(stopwatch.Elapsed.TotalSeconds, 0)}");
                await Task.Delay(1000);
            }

            foreach (int e in infoGetTask.Result)
            {
                Console.WriteLine(e);
            }
        }

        public async Task<IEnumerable<int>> GetAllInformation()
        {
            await Task.Delay(3000);

            return new int[3] { 1, 2, 3 };
        }

Note that for simplicity I'm only checking for IsCompleted but there are two other possible flags that can/should be checked. 请注意,为简单起见,我仅检查IsCompleted,但可以/应该检查另外两个可能的标志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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