none
單執行緒程式卻發生占用問題 RRS feed

  • 一般討論

  • 手邊有一支是單執行緒的console程式,在執行時經常會出現這樣的訊息:

    The process cannot access the file 'D:\XXX.jpg' because it is being used by another process.

    此程式是每天用排程自動執行一次,但這個情況並非每天都會出現...

    主要執行程式碼如下,希望有人可以幫忙解惑為什麼會發生這種現象,謝謝

    public void run()
            {
                xmldoc.Load("config.xml");
                runMode = xmldoc.SelectSingleNode("//root/RUN_MODE").InnerText;
                dayReport = xmldoc.SelectSingleNode("//root/DAY_REPROT").InnerText;
                weekReport = xmldoc.SelectSingleNode("//root/WEEK_REPROT").InnerText;
                monthReport = xmldoc.SelectSingleNode("//root/MONTH_REPROT").InnerText;
                factoryNo = xmldoc.SelectSingleNode("//root/FACTORY_NO").InnerText;
                fstream = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "LOG\\" + runMode + "-" + DateTime.Now.ToString("yyyyMMdd") + ".txt", FileMode.Append);
                swriter = new StreamWriter(fstream, Encoding.Default);
                string sendToCN = string.Empty;
                string sendToTW = string.Empty;
                string to = string.Empty;
                string[] rumModeValue = runMode.Split(',');
                string[] dayReportValue = dayReport.Split(',');
                string[] weekReportValue = weekReport.Split(',');
                string[] monthReportValue = monthReport.Split(',');
                string[] factoryNoValue = factoryNo.Split(',');
                
                for (int i = 0; i < rumModeValue.Length; i++)
                {
                    if (rumModeValue[i].Equals("DAY"))
                    {
                        for (int j = 0; j < dayReportValue.Length; j++)
                        {
                            if (dayReportValue[j].Equals("R1"))
                            {
                                for (int z = 0; z < factoryNoValue.Length; z++)
                                {
                                    DataSet oDs = Service.QryReportRuleConfig001(factoryNoValue[z], "R1", "DAY");
                                    if (oDs.Tables[0].Rows.Count != 0)
                                    {
                                        for (int n = 0; n < oDs.Tables[0].Rows.Count; n++)
                                        {
                                            ReportViewer ReportViewer1 = new ReportViewer();
                                            try
                                            {
                                                title = oDs.Tables[0].Rows[n]["SEND_TITLE"].ToString().Trim();
                                                sendToCN = GetMailInfo.GetSendToCNUser(oDs.Tables[0].Rows[n]["SEND_TO_CN"].ToString().Trim());
                                                sendToTW = GetMailInfo.GetSendToTWUser(oDs.Tables[0].Rows[n]["SEND_TO_TW"].ToString().Trim());
                                                to = GetMailInfo.GetSendToUser(sendToCN + ";" + sendToTW);
                                                if (oDs.Tables[0].Rows[n]["CONDITION_STATION_ID"].ToString().Trim().Equals(string.Empty))
                                                {
                                                    throw new Exception("ID:" + oDs.Tables[0].Rows[n]["TYPE_ID"].ToString().Trim() + "站别不能為空!");
                                                }
                                                string stationIdList = GetMailInfo.GetStationId(oDs.Tables[0].Rows[n]["CONDITION_STATION_ID"].ToString().Trim());
                                                int stationIdCount = GetMailInfo.GetStationCount(stationIdList);
                                                string body = "";
    
                                                DataSet oDs0 = new DataSet();
                                                oDs0 = Service.QryYieldRateWipInfo(string.Format("{0:yyyy/MM/dd}", DateTime.Now.AddDays(-12)), string.Format("{0:yyyy/MM/dd}", DateTime.Now.AddDays(-1)), factoryNoValue[z], stationIdList, "", "", "DAY", "S", stationIdCount);
                                                string reportPath = AppDomain.CurrentDomain.BaseDirectory + "RDLC\\YieldRate Report.rdlc";
                                                ReportViewer1.Reset();
                                                ReportDataSource rds1 = new ReportDataSource("YieldRateWip", oDs0.Tables[0]);
                                                ReportViewer1.LocalReport.ReportPath = reportPath;
                                                ReportViewer1.LocalReport.EnableHyperlinks = true;
                                                ReportViewer1.LocalReport.DataSources.Clear();
                                                ReportViewer1.LocalReport.DataSources.Add(rds1);
                                                ReportViewer1.LocalReport.Refresh();
    
                                                byte[] bytes = ReportViewer1.LocalReport.Render("Image", "<DeviceInfo><OutputFormat>PNG</OutputFormat><PageWidth>31cm</PageWidth><PageHeight>29.7cm</PageHeight><MarginTop>1cm</MarginTop><MarginLeft>1cm</MarginLeft><MarginRight>1cm</MarginRight><MarginBottom>1cm</MarginBottom></DeviceInfo>");
    
                                                FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "LogJpgExcel\\YieldRate Report By Day.jpg", FileMode.Create);
                                                fs.Write(bytes, 0, bytes.Length);                                            
                                                fs.Close();
                                                fs.Dispose();
    
                                                byte[] bytes1 = ReportViewer1.LocalReport.Render("EXCEL");
    
                                                FileStream fs1 = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "LogJpgExcel\\YieldRate Report By Day.xls", FileMode.Create);
                                                fs1.Write(bytes1, 0, bytes1.Length);                                            
                                                fs1.Close();
                                                fs1.Dispose();
    
                                                string[] excel = { AppDomain.CurrentDomain.BaseDirectory + "LogJpgExcel\\YieldRate Report By Day.xls" };
                                                string[] image = { AppDomain.CurrentDomain.BaseDirectory + "LogJpgExcel\\YieldRate Report By Day.jpg;918.0;882.6" };
    
                                                mail.MailSend(from, to, "", title, body, excel, "", image);
                                                swriter.WriteLine(DateTime.Now.ToString() + "-固定報表-R1-DAY-郵件發送OK!(" + factoryNoValue[z] + "-" + oDs.Tables[0].Rows[n]["SEND_TITLE"].ToString().Trim()+")");
                                                Console.WriteLine(factoryNoValue[z]+"-"+oDs.Tables[0].Rows[n]["SEND_TITLE"].ToString().Trim()+"-"+"郵件發送OK!");
                                            }
                                            catch (Exception e)
                                            {
                                                swriter.WriteLine(DateTime.Now.ToString() + "-固定報表-R1-DAY-" + e.Message);
                                                Console.WriteLine(e.Message);
                                            }
                                            finally
                                            {
                                                ReportViewer1.LocalReport.ReleaseSandboxAppDomain();
                                            }
                                        }
                                    }
    
                                }
                            }
                        }
                    }


    2015年10月5日 上午 08:40

所有回覆

  • 這裡看不到你的 Mail 是什麼 object,是.NET 自帶的 smtpClient還是第三方的?

    如果是自帶的,會否是 MailSend裡面是用 SendAsync?

    因為看你的code,就只有 MailSend裡是在用 image ,而它還沒完成 send之前,如果 code已經到第二次的 loop,準確再重寫那個 image,問題便出現了

    所以你要看看會不會 MailSend是 Async或 Sync的


    大家一齊探討、學習和研究,謝謝!
    MCSD, MCAD, MCSE+I, MCDBA, MCDST, MCSA, MCTS, MCITP, MCPD,
    MCT, Microsoft Community Star(TW & HK),
    Microsoft MVP for VB.NET since 2003
    My MSMVP Blog

    請記得將對您有幫助的回覆 標示為解答 以幫助其他尋找解答及參與社群討論的朋友們。
    Please remember to click Mark as Answer on the post that helps you. This can be beneficial to other community members reading the thread.

    2015年10月5日 上午 09:57
  • 不然就檔名加個亂數讓它不重覆
    2015年10月6日 上午 02:21