gpt4 book ai didi

c# - 使用 async await c# 轮询电子邮件

转载 作者:行者123 更新时间:2023-11-30 12:31:30 26 4
gpt4 key购买 nike

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

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

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

    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()
{
...............................................................................
}

最佳答案

除了在 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();
}

}

}
}

关于c# - 使用 async await c# 轮询电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13407095/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com