许多长时间运行的任务,最后都会发生IAsyncResult回调

时间:2014-02-26 22:16:44

标签: c# multithreading sharepoint

我已经把头发拉了几个星期了,我需要一些帮助。这是一个SharePoint实用程序,可将RDL文件复制到项目站点。为什么我的IAsyncResult.EndInvokes在处理整个列表后被调用?平均而言,我可以在10秒内将所有RDL文件复制到1个项目站点。考虑到这一点,我希望在一分钟内在IAsyncResult方法内点击我的断点。相反,断点不会在所有项目都被复制到所有项目之后才会出现,然后断点就会快速连续发生。我在这做错了什么?

我不得不使用.NET 3.5,因此不能选择TAP处理:(

代表:

public delegate string CopyReportsParallel(string targetSiteUrl, List<SourceReportInfo> reports, EditorSettings settings);

此方法编译RDL和目标项目站点的列表。对于每个目标站点,它创建一个代理来处理复制逻辑:

private static void bw_DoWork(Object sender, DoWorkEventArgs e)
    {            
        int workerIndex = bwObject.targetProjectSiteUrls.Count;
        _totalCount = bwObject.targetProjectSiteUrls.Count;
    foreach (string s in bwObject.targetProjectSiteUrls)
    {
        if (cancelled)
            break;

        //Get a delegate for the operation
        CopyReportsParallel d = new CopyReportsParallel(ParallelCopyLogic);
        IAsyncResult ar = d.BeginInvoke(s, bwObject.reports, bwObject.settings, BackgroundWorkerIsDone, d);               
    }

    waitHandle.WaitOne();

}

这是我的回电方法。理想情况下,我希望尽可能多的线程进行异步处理,并在完成后立即报告,以便我可以使用进度条更新网页。

    private static void BackgroundWorkerIsDone(IAsyncResult ar)
    {
        CopyReportsParallel d = (CopyReportsParallel)ar.AsyncState;

        string result = d.EndInvoke(ar);

        lock ((_lockObject))
        {
            _completedCount += 1;

            if (logTheHistory)
            {
                int completedPercent = _completedCount * 100 / _totalCount;
                string report = result + Environment.NewLine + "Update - " + completedPercent.ToString() + "% Complete " + " # of Projects Completed: " + _completedCount.ToString();

                bw.ReportProgress(completedPercent, report);
            }

            if (_completedCount == _totalCount)
            {
                waitHandle.Set();
            }    
        }
    }

并行复制逻辑(按请求):

private static string ParallelCopyLogic(string targetSiteUrl, List<SourceReportInfo> reports, EditorSettings settings)
        {
            string _runDetail = "";
            _runDetail += (System.DateTime.Now.ToString() + " - Working on Project: " + targetSiteUrl + Environment.NewLine);

            using (_reportSvc = new ReportingService2010())
            {
                _reportSvc.Url = reportSvcURl;
                _reportSvc.Credentials = System.Net.CredentialCache.DefaultCredentials;
                _reportSvc.PreAuthenticate = true;
                _reportSvc.Timeout = Timeout.Infinite;

                using (SPSite targetSite = new SPSite(targetSiteUrl))
                using (SPWeb targetWeb = targetSite.OpenWeb())
                {
                    foreach (SourceReportInfo reportInfo in reports)
                    {
                        try
                        {
                            SPDocumentLibrary targetReportLibrary = targetWeb.Lists[reportInfo.SourceReport.ParentList.RootFolder.Name] as SPDocumentLibrary;
                            SPFile targetReportFile = targetReportLibrary.RootFolder.Files.Add(reportInfo.SoureReportUrl, reportInfo.SourceReportFileBytes, reportInfo.SourceReport.Properties, true);
                            SPListItem targetReport = targetReportFile.GetListItem();

                            string sourceURL = reportInfo.SourceReport.Web.Url + "/" + reportInfo.SourceReport.Url;
                            string destinationURL = targetReport.Web.Url + "/" + targetReport.Url;
                            string targetListUrl = targetReport.Web.Url + "/" + targetReport.ParentList.RootFolder.Name;

                            bool dsUpdated = false;
                            bool paramUpdated = false;
                            bool ddUpdated = false;

                            if (!targetReport.HasUniqueRoleAssignments)
                                targetReport.BreakRoleInheritance(true);

                            foreach (SPRoleAssignment role in reportInfo.RoleAssignments)
                                targetReport.RoleAssignments.Add(role);

                            targetReport.Update();


                            // Update copied Items
                            if (reportInfo.SoureReportUrl.EndsWith(".rdl"))
                            {
                                SPSecurity.RunWithElevatedPrivileges(new SPSecurity.CodeToRunElevated(delegate()
                                {
                                    ReportService.DataSource[] sourceDataSources = _reportSvc.GetItemDataSources(sourceURL);
                                    ReportService.DataSource[] destDataSources = _reportSvc.GetItemDataSources(destinationURL);

                                    for (int i = 0; i < sourceDataSources.Length; i++)
                                    {
                                        DataSourceReference sourceDs = sourceDataSources[i].Item as DataSourceReference;
                                        DataSourceDefinition sourceDef = sourceDataSources[i].Item as DataSourceDefinition;
                                        DataSourceDefinition destDef = destDataSources[i].Item as DataSourceDefinition;


                                        // Updates the target data source references
                                        if (sourceDs != null && sourceDs.Reference != null && sourceDataSources[i].Name == destDataSources[i].Name)
                                        {
                                            string sourceDsName = System.IO.Path.GetFileName(sourceDs.Reference);

                                            destDataSources[i].Item = new DataSourceReference { Reference = targetListUrl + "/" + sourceDsName };
                                            dsUpdated = true;
                                        }

                                        //Updates the target data source definitions
                                        else if (sourceDef != null && destDef != null && sourceDataSources[i].Name == destDataSources[i].Name)
                                        {
                                            //Set data source credentials
                                            destDef.Enabled = true;
                                            destDef.CredentialRetrieval = sourceDef.CredentialRetrieval;
                                            destDef.ImpersonateUser = sourceDef.ImpersonateUser;
                                            destDef.WindowsCredentials = sourceDef.WindowsCredentials;

                                            if (settings != null && destDef.CredentialRetrieval == CredentialRetrievalEnum.Store)
                                            {
                                                destDef.UserName = settings.DataAccessUserName;
                                                settings.GetDataAccessPassword(destDef);
                                            }

                                            destDataSources[i].Item = destDef;
                                            ddUpdated = true;
                                        }
                                    }

                                    if (dsUpdated | ddUpdated)
                                    {
                                        _reportSvc.SetItemDataSources(destinationURL, destDataSources);
                                        dsUpdated = false;
                                        ddUpdated = false;
                                    }

                                    //Updates the target report's project code default parameter
                                    ItemParameter[] parameters = _reportSvc.GetItemParameters(destinationURL, null, false, null, null);

                                    foreach (ItemParameter item in parameters)
                                    {
                                        //Have to check if prompt text is empty as this API doesnt expose hidden property
                                        if (item.Name.ToLower() == "projectcode" && string.IsNullOrEmpty(item.Prompt) && item.DefaultValues.Length == 1)
                                        {
                                            item.DefaultValues[0] = targetWeb.Name;
                                            paramUpdated = true;

                                            break;
                                        }
                                    }

                                    if (paramUpdated)
                                    {
                                        _reportSvc.SetItemParameters(destinationURL, parameters);
                                        paramUpdated = false;
                                    }
                                }));
                            }
                            else if (reportInfo.SoureReportUrl.EndsWith(".rsds"))
                            {
                                //Update Shared Datasets
                                DataSourceDefinition sourceDef = _reportSvc.GetDataSourceContents(sourceURL);
                                DataSourceDefinition destinationDef = _reportSvc.GetDataSourceContents(destinationURL);

                                destinationDef.Enabled = true;
                                destinationDef.CredentialRetrieval = sourceDef.CredentialRetrieval;
                                destinationDef.ImpersonateUser = sourceDef.ImpersonateUser;
                                destinationDef.WindowsCredentials = sourceDef.WindowsCredentials;

                                if (settings != null && destinationDef.CredentialRetrieval != CredentialRetrievalEnum.Integrated)
                                {
                                    destinationDef.UserName = settings.DataAccessUserName;
                                    settings.GetDataAccessPassword(destinationDef);
                                }

                                _reportSvc.SetDataSourceContents(destinationURL, destinationDef);
                            }

                            _runDetail += (System.DateTime.Now.ToString() + " - Finished updating report:  " + targetReport.Name.ToString() + Environment.NewLine);


                        }
                        catch (Exception ex)
                        {
                            _runDetail += (System.DateTime.Now.ToString() + " - There was an error on project: " + targetSiteUrl + Environment.NewLine);
                            throw new InvalidOperationException(string.Format("Error while updating report {0} on Project Site {1}. Exception:{2}", reportInfo.SoureReportUrl, targetSiteUrl, ex.Message), ex);

                        }
                    }
                }
            }
            return _runDetail;
        }

请告诉我您的想法或您是否需要更多信息。我看了看,看了看,所以我不想让任何人“在这里做我的功课”。我很想从一些经验丰富的程序员那里学到一两件事。

谢谢!

1 个答案:

答案 0 :(得分:1)

这种逻辑没有错。编译器将触发ASYNC代理,同时接收其IASYNC回调。