4

我正在创建一个控制台应用程序,它将:

  1. 调用一个方法来检查一个电子邮件帐户(我已经完成了这一步)
  2. 将附件转换为pdf(我已完成此步骤)
  3. 然后一旦转换完成等待30秒
  4. 不断重复前面3个步骤

我已经完成了方法中的步骤 1) 和 2) ProcessMailMessages()。以下代码有效,但我想知道我是否走在正确的轨道上,还是有更好的方法来轮询电子邮件客户端?

    private static int secondsToWait = 30 * 1000;

    static void Main(string[] args)
    {
        bool run = true;
        do
        {
            try
            {
                Task theTask = ProcessEmailTaskAsync();
                theTask.Wait();
            }
            catch (Exception e)
            {
                Debug.WriteLine("<p>Error in Client</p> <p>Exception</p> <p>" + e.Message + "</p><p>" + e.StackTrace + "</p> ");
            }
            GC.Collect();

        } while (run);

    }

    static async Task ProcessEmailTaskAsync()
    {
        var result = await EmailTaskAsync();
    }

    static async Task<int> EmailTaskAsync()
    {
        await ProcessMailMessages();
        await Task.Delay(secondsToWait);
        return 1;
    }

    static async Task ProcessMailMessages()
    {
        ...............................................................................
    }
4

3 回答 3

2

您可以使用计时器,而不是在 main 中循环。主要是,您将设置计时器,然后您可以等待 Console.Readline() 以防止控制台关闭。

编辑——这是一个例子


using System;

namespace ConsoleApplication1
{
    class Program
    {
        private const int MilliSecondsToWait = 30000;
        private static System.Timers.Timer EmailTimer;

        static void Main(string[] args)
        {
            EmailTimer = new System.Timers.Timer(MilliSecondsToWait);
            EmailTimer.Elapsed += EmailTimer_Elapsed;
            EmailTimer.Start();

            Console.WriteLine("Press Enter to quit.");
            Console.ReadLine();
            // if you hit enter, the app will exit.  It is possible for the user to exit the app while a mail download is occurring.  
            // I'll leave it to you to add some flags to control that situation (just trying to keep the example simple)
        }

        private static void EmailTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            // stop the timer to prevent overlapping email downloads if the current download takes longer than MilliSecondsToWait
            EmailTimer.Stop();
            try
            {
                Console.WriteLine("Email Download in progress.");
                // get your email.
            }
            catch (System.Exception ex)
            {
                // handle any errors -- if you let an exception rise beyond this point, the app will be terminated.
            }
            finally
            {
                // start the next poll
                EmailTimer.Start();
            }

        }

    }
}

于 2012-11-15T22:51:17.827 回答
0

您的代码运行良好,它避免使用计时器!并且还使您的代码与 async/await (TPL) 异步。你在正确的轨道上!

于 2012-11-19T15:54:15.197 回答
0

这是对 async/await 的无偿使用,因为它是一个控制台应用程序,而您只是阻塞,直到调用完成为止。不妨从你的 do/while 循环中调用 ProcessMailMessages() 并完成它。

于 2013-09-13T21:08:46.563 回答