Успешная отправка электронного письма, но почему программа c # не переходит к следующему или завершена? - PullRequest
0 голосов
/ 21 мая 2018

При режиме отладки, после var response = await client.SendEmailAsync(mail);.Остальная часть программы больше не может работать.

Как решить эту проблему?

class Program
{
    private SqlConnection dbConnection;
    private DBSetting dbSetting;
    private UserSession usession;

    static void Main(string[] args)
    {




        SqlConnection myConnection = new SqlConnection(xxxxxAPIURL);
        myConnection.Open();

        Program program = new Program(myConnection, dbSetting, usession);

        string emailcontent = "";

        foreach (string targetDB in ipArray)
        {



            // Extra ItEM Type
            DataTable DT_ExtraItemType = program.GetExtraItemTypeFromTarget(SQLDBName, targetDB);

            emailcontent += "<br /> <br />Extra Item Type from " + targetDB;

            string extraitemtypemsg = "";

            foreach (DataRow DataTable_ExtraItemtype in DT_ExtraItemType.Rows)
            {
                string msg = "";

                string extra_targetdb = targetDB.ToString();
                string extra_ItemType = DataTable_ExtraItemtype["ItemType"].ToString();

                msg = "<br />In " + extra_targetdb + " ,ItemType: " + extra_ItemType;

                emailcontent += msg;
            }

            //AutoSendMessage(extraitemtypemsg, targetDB).Wait();


            DataTable DT_ExtraItemCategory = program.GetExtraItemCategoryFromTarget(SQLDBName, targetDB);

            emailcontent += "<br /> <br />Extra Item Category from " + targetDB;

            string extraitemcategoryemsg = "";
            foreach (DataRow DataTable_ExtraItemCategory in DT_ExtraItemCategory.Rows)
            {
                string msg = "";
                string extra_targetdb = targetDB.ToString();
                string extra_ItemCategory = DataTable_ExtraItemCategory["ItemCategory"].ToString();

                msg = "<br />In " + extra_targetdb + " ,Item Category: " + extra_ItemCategory;
                //extraitemcategoryemsg += msg;
                emailcontent += msg;
            }

            emailcontent += "<br /> <br />Extra ItemCode from " + targetDB;


            DataTable DT_AddNewItem = program.GetNewItem(SQLDBName, targetDB);

            foreach (DataRow DataTable_AddNewItem in DT_AddNewItem.Rows)
            {
                string addnewitem_itemcode = DataTable_AddNewItem["ItemCode"].ToString();
                string result = program.AddNewItem(addnewitem_itemcode, dbSetting, usession, targetdbSetting, targetusession);

                if (result != "success!")
                    Console.WriteLine("Fail to Create New Item " + addnewitem_itemcode + " .\n" + result.ToString());
                else Console.WriteLine(result.ToUpper() +"New Item Created : "+ addnewitem_itemcode + " .");
            }
        }

        program.AutoSendMessage(emailcontent).Wait();
    }

    public Program(SqlConnection connection, DBSetting dbset, UserSession users)
    {
        dbConnection = connection;
        dbSetting = dbset;
        usession = users;
    }


    //DataTable Extra Item Type from TargetDB and mention User to Check/Remove It manually
    private DataTable GetExtraItemTypeFromTarget(string SourceDB, string targetDB)
    {
        DataTable dt = new DataTable();

        string sql = "select t.ItemType ItemType from " + targetDB + ".dbo.ItemType t where " +
        "not exists(select * from " + SourceDB + ".dbo.ItemType s where t.ItemType = s.ItemType) ";
        SqlCommand ExtraItemTypeCommand = new SqlCommand(sql, dbConnection);//using myconnection
        ExtraItemTypeCommand.CommandTimeout = 180; /*Excute Time Out Second*/
        SqlDataReader ExtraItmeTypeReader = ExtraItemTypeCommand.ExecuteReader();
        dt.Load(ExtraItmeTypeReader);

        return dt;

    }

    // DataTable Extra Item Category from TargetDB and mention User to Check/Remove It manually
    private DataTable GetExtraItemCategoryFromTarget(string SourceDB, string targetDB)
    {
        DataTable dt = new DataTable();

        string sql = "select t.ItemCategory ItemCategory from " + targetDB + ".dbo.ItemCategory t where " +
        "not exists(select * from " + SourceDB + ".dbo.ItemCategory s where t.ItemCategory = s.ItemCategory) ";
        SqlCommand ExtraItemTypeCommand = new SqlCommand(sql, dbConnection);//using myconnection
        ExtraItemTypeCommand.CommandTimeout = 180; 
        SqlDataReader ExtraItemCategoryReader = ExtraItemTypeCommand.ExecuteReader();
        dt.Load(ExtraItemCategoryReader);

        return dt;

    }


    private static  async Task AutoSendMessage(string Message)
    {

        try
        {

            var client = new SendGridClient("API_KEY");


            var from = new EmailAddress("xxxxxx", "xxxxxxx");
            var subject = "Extra Information from API_Item Master(Item, ItemCode, Item Category) Program ";
            var messagedetail = Message;
            var to = new EmailAddress("xxxxxxxx", "xxxx");
            var plainTextContent = "Hello, Email from the helper !" + messagedetail;
            var htmlContent = "<strong>Please check the Following Information:- </strong>" + messagedetail;




            var mail = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
            var response = await client.SendEmailAsync(mail);

        }
        catch(Exception ex) 
        {
                Console.WriteLine(ex.Message);
        }

    }
}

}

Ответы [ 2 ]

0 голосов
/ 21 мая 2018

Если вы используете языковые функции C # 7.1 (возможно, вам придется включить их, отредактировав свой .csproj), вы можете использовать асинхронный метод Main:

static async Task Main(string[] args)
{
    await program.AutoSendMessage(emailcontent);
}

Чтобы включить функцию C # 7.1, янеобходимо отредактировать мой файл .csproj.

  1. Открыть .csporj с помощью блокнота
  2. Найти <TargetFrameworkVersion>SOMETHING</TargetFrameworkVersion>
  3. Добавить новую строку под ним, которая гласит: <LangVersion>7.1</LangVersion>
  4. Сохраните ваш .csproj
  5. Теперь вы можете использовать асинхронный режим Main.
0 голосов
/ 21 мая 2018

Проблема: это может быть потому, что вы блокируете поток пользовательского интерфейса.Но поскольку вы не предоставили общий доступ ко всему коду, я не уверен.

Исправление: попробуйте ConfigureAwait (false) при вызове

var response = await client.SendEmailAsync(mail).ConfigureAwait(false);

Ссылка: https://github.com/sendgrid/sendgrid-csharp/issues/423#issuecomment-287853152

...