как повысить скорость чтения электронных писем c # веб-приложения - PullRequest
0 голосов
/ 26 сентября 2018

Я написал код c # для чтения электронных писем из моей учетной записи gmail, используя библиотеку openpop.net, и сохранял их в базе данных.Все идет хорошо, но загрузка писем идет очень медленно.Я попытался использовать параллельный цикл .for, но он выдал ошибку:

Метод записи не может быть запущен, пока работает другой метод записи

Есть ли способ использовать параллельную обработкув этом случае?

Это моя функция чтения электронных писем:

public void Read_Emails()


    {


        Pop3Client pop3Client;

        if (Session["Pop3Client"] == null)
        {

            pop3Client = new Pop3Client();
            pop3Client.Connect("pop.gmail.com", 995, true);
            pop3Client.Authenticate(usermail, pwd, AuthenticationMethod.UsernameAndPassword);
            Session["Pop3Client"] = pop3Client;
        }
        else
        {
            pop3Client = (Pop3Client)Session["Pop3Client"];
        }
 int   count = pop3Client.GetMessageCount();
        for (int i = count; i >= 1; i--)
        {
            Message message = pop3Client.GetMessage(i);
            FFromAdress = message.Headers.From.Address;
            ddate = message.Headers.DateSent;
            MMessageNO = i; //message.Headers.MessageId;
            List<MessagePart> attachments = message.FindAllAttachments();
            DataTable dt = get_Health_Institutions();
            DataTable dt1 = get_INTERIOR_Institutions();
            foreach (DataRow row in dt.Rows){health_result = FFromAdress.Equals(row["mail"]);}
            foreach (DataRow row in dt1.Rows){interior_result = FFromAdress.Equals(row["mail"]);}
            bool result = FFromAdress.Equals("sersersetrerttrtail.com");
            if (health_result == true) //|| interior_result == true)
            {   SSubject = message.Headers.Subject.Split(':')[1];
                MessagePart body = message.FindFirstHtmlVersion();
                body = message.FindFirstPlainTextVersion();
                if (body != null)
                {
                    string BBody1 = body.GetBodyAsText();
                    BBody = BBody1.Replace(' ', '\n');
                }
                if (attachments.Count == 0)
                {
                    atta_count = 0;
                    AAtachments_Path = SSubject;
                    if (CHKsubjectexist_Health_Date(SSubject) == 0)
                    { insertmail_health_date(FFromAdress, SSubject, ddate, BBody, AAtachments_Path, MMessageNO, atta_count); }
                }
                else
                { for (int m = 0; m < attachments.Count; m++)
                    {
                        atta_count = attachments.Count;
                        if (health_result == true & interior_result == false)
                        { imagename = "healthRESULT_answer" + m+".jpg"; }
                        Foldername = SSubject.Trim();
                        AAtachments_Path = Foldername;
                        byte[] bdata = attachments[m].Body;
                        string folderpathh = "d:\\asdf\\" + Foldername;
                        System.IO.Directory.CreateDirectory(folderpathh);
                        string pathh = folderpathh + "\\" + imagename;
                        System.IO.File.WriteAllBytes(pathh, bdata);
                        ////write image
                        String st = Server.MapPath(imagename);
                        FileStream fs = new FileStream(st, FileMode.Create, FileAccess.Write);
                        fs.Write(bdata, 0, bdata.Length);
                        fs.Close();
                      }
                if (CHKsubjectexist_Health_final(SSubject) == 0)
                    { insertmail_Health_Final(FFromAdress, SSubject, ddate, BBody, AAtachments_Path, MMessageNO, atta_count); }
                }

            }
                else if (interior_result == true)
            {
                SSubject = message.Headers.Subject.Split(':')[1];
                MessagePart body = message.FindFirstHtmlVersion();
                body = message.FindFirstPlainTextVersion();
                if (body != null)
                {
                    string BBody1 = body.GetBodyAsText();
                    BBody = BBody1.Replace(' ', '\n');
                }
                if (attachments.Count == 0)
                {
                    atta_count = 0;
                    AAtachments_Path = SSubject;
                }
                else
                {
                    for (int m = 0; m < attachments.Count; m++)
                    {
                        atta_count = attachments.Count;
                        imagename = "Interior_answer" + m+".jpg"; 
                        Foldername = SSubject.Trim();
                        AAtachments_Path = Foldername;
                        byte[] bdata = attachments[m].Body;
                        string folderpathh = "d:\\asdf\\" + Foldername;
                        // System.IO.Directory.CreateDirectory(folderpathh);
                        string pathh = folderpathh + "\\" + imagename;
                        System.IO.File.WriteAllBytes(pathh, bdata);
                        ////write image
                        String st = Server.MapPath(imagename);
                        FileStream fs = new FileStream(st, FileMode.Create, FileAccess.Write);
                        fs.Write(bdata, 0, bdata.Length);
                        fs.Close();

                    }

                }
                if (CHKsubjectexist_Interior(SSubject) == 0)
                     { insertmail_interior(FFromAdress, SSubject, ddate, BBody, AAtachments_Path, MMessageNO, atta_count); }
            }
            else if (result == true)
            {
                SSubject = message.Headers.Subject;
                if (CHKsubjectexist(SSubject) == 0)
                {
                    MessagePart body = message.FindFirstHtmlVersion();
                    if (body != null)
                    {
                        BBody = body.GetBodyAsText();
                    }
                    else
                    {
                        body = message.FindFirstPlainTextVersion();
                        if (body != null)
                        {
                            BBody = body.GetBodyAsText();
                        }
                    }
                    if (attachments.Count == 0)
                    {
                        AAtachments_Path = " ";
                    }
                    else
                    {
                        foreach (MessagePart attachment in attachments)
                        {
                            atta_count = attachments.Count;
                            string filenameee = attachment.FileName;
                            imagename = filenameee.Split('/', '/')[3];
                            Foldername = SSubject;
                            AAtachments_Path = Foldername;
                            byte[] bdata = attachment.Body;
                            string folderpathh = "d:\\asdf\\" + Foldername;
                            System.IO.Directory.CreateDirectory(folderpathh);
                            string pathh = folderpathh + "\\" + imagename;
                            System.IO.File.WriteAllBytes(pathh, bdata);
                            ////write image
                            String st = Server.MapPath(imagename);
                            FileStream fs = new FileStream(st, FileMode.Create, FileAccess.Write);
                            fs.Write(bdata, 0, bdata.Length);
                            fs.Close();
                        }
                    }
                    if (CHKsubjectexist(SSubject) == 0)
                    { insertmail(FFromAdress, SSubject, ddate, BBody, AAtachments_Path, MMessageNO, atta_count); }

                }

            }

        }

    }
...