在做一个项目的过程中,发现GP运算方法

Execute(string name, IVariantArray parameters, ITrackCancel trackCancel) 与Execute(IGPProcess process, ITrackCancel trackCancel)
的执行效率竟然有差别,很是奇怪,后用反编译软件,查看dll中的代码,发现两者确实不同,代码如下:

        public object Execute(string name, IVariantArray parameters, ITrackCancel trackCancel)
{
return this._gp.Execute(name, parameters, trackCancel);
}
        public object Execute(IGPProcess process, ITrackCancel trackCancel)
{
IVariantArray iva;
if (this._isRemote)
{
iva = (this._ctx.CreateObject("esriSystem.VarArray") as IVariantArray);
}
else
{
iva = new VarArrayClass();
}
return this.ExecuteInner(process, trackCancel, this._gp, iva);
}
private object ExecuteInner(IGPProcess process, ITrackCancel trackCancel, IGeoProcessor igp, IVariantArray iva)
{
object result = null;
try
{
this.AddToolbox(Utils.MapToolboxConfigDir(process.ToolboxDirectory) + "\\" + process.ToolboxName);
object[] parameterInfo = process.ParameterInfo;
for (int i = ; i < parameterInfo.Length; i++)
{
if (parameterInfo[i] != null)
{
iva.Add(parameterInfo[i]);
}
else
{
iva.Add("#");
}
}
result = this._gp.Execute(process.ToolName + "_" + process.Alias, iva, trackCancel);
for (int j = ; j < iva.Count; j++)
{
object obj = iva.get_Element(j);
if (!(obj is string) || !((string)obj == "#"))
{
parameterInfo[j] = obj;
}
}
}
catch (Exception)
{
throw;
}
finally
{
Marshal.ReleaseComObject(iva);
}
return result;
}

从两者的代码中,可以看出,三参数的Execute的执行效率要远远高于两参数的Execute。原因很明显,两参数的Execute执行了很多本可以无须执行的代码。三参数直接执行运算,效率就高了。

代码中 _gp接口,实现类是ESRI.ArcGIS.Geoprocessing.GeoProcessorClass.所以在执行GP的时候,完全可以不需要定义ESRI.ArcGIS.Geoprocessor中的Geoprocessor(大多时间我们使用这个类),而是直接定义GeoProcessorClass,运行三参数方法来实现GP的运算。效果更好点

从网上也查找到一些相关的资料,仅供参考!

引用自链接!

http://blog.csdn.net/liuguobo/article/details/16965987

In this topic

How to run a geoprocessing tool(这个地方在仔细整理下!!)

Each geoprocessing tool has a fixed set of parameters that provide the tool with the information it needs for execution. Tools usually have input parameters that define the dataset or datasets that will typically be used to generate new output data. Parameters have the following important properties:
  • Name—Each tool parameter has a unique name.
  • Type—The type of data expected, such as a feature class, integer, string, and raster.
  • Required—Either a value must be provided for a parameter, or it is optional.
Each tool has a documentation page known as a tool reference page.For more information about parameters, see Interpreting a tool reference page.(Interpreting:解释。在这个页面介绍了怎么快速定位“工具”,找到工具名称和工具参数信息,一定要了解这个专题上的信息,你才能很好地使用ArcGIS的工具。其实,你在使用ArcMap的系统工具的时候,在工具的帮助文档里,就能找到那个工具的名称,别名,参数,还有部分的Python代码。)
When a tool is used in a program, its parameter values must be set correctly so it can execute when the program runs. The documentation of each tool clearly defines its parameters and properties. Once a valid set of parameter values is provided, the tool is ready to be executed.
Parameters are specified as strings or objects. Strings are text values that uniquely identify a parameter value, such as a path to a dataset or a keyword. Most tool parameters can be specified as a simple string. However, complex parameters, such as a spatial reference, can be easier to specify with an object. Each tool has its own parameter types.To get complete information on a particular tool, review the tool reference page. Interpreting a tool reference page explains how to read a tool reference page and extract information to use in .NET.
两种方法的区别:Geoprocessing & geoprocessor 
You can run a geoprocessing tool by using the Geoprocessing library methods or by the geoprocessor managed assembly methods. For information about the basic differences between the two approaches, seeExecuting tools. In both cases, the Execute method of the geoprocessor is called.
取消即终止功能通常设为null
The Execute method uses a null reference instead of an ITrackCancel interface. The ITrackCancel interface provides access to properties and methods that determine if a cancellation has been executed by the user and also allows developers to specify what actions constitute a cancellation. Both approaches are elaborated(详细阐述如下) with the following examples.

Using the geoprocessing assembly(是一个COM Interop程序集)

The geoprocessing assembly is the Component Object Model (COM) interop of the Geoprocessing type library(什么是COM Interop?COM Interop看上去象是介乎于COM和.Net之间的一条纽带,一座桥梁。). The Execute method of theIGeoProcessor2 interface of the library is used to run a tool.
The following are the generic steps to execute a tool:
  1. Add a reference toESRI.ArcGIS.Geoprocessingto your project. This is the only reference you need if you use the geoprocessing assembly.
  2. Create thegeoprocessor object(通过IGeoProcessor2接口 ,注意:P大写,且是第2接口).
  3. Add the path to the custom toolbox if you are running a custom tool.
  4. Create an IVariantArray and populate(板上组装、填入) it with tool parameter values. The IVariantArray is available through the esriSystem library(参数值通过IVariantArray 设置).
  5. Call the Execute methodon the geoprocessor.
The process is the same if you run a system tool or a custom tool.
确保填入参数有正确的设置顺序:Make sure you maintain the order of parameters as specified in the tool reference page when populating the variant array. Follow the syntax section of the tool reference page (see link at the bottom), it shows the correct ordering of parameters.
如果你想跳过可选参数,你只需要将它们填入一个空字符串,如"":If you want to skip an optional parameter, just add an empty string to the variant array in correct order. For example, if a tool's third, fourth and fifth parameters are optional and you want to pass value only to the fifth parameter, then you have to pass empty strings to the third and fourth parameters to maintain correct ordering.
如果你填入空字符串,处理工具将使用默认值:Passing an empty string instructs the tool to use the default value of that parameter.
正确的参数设置顺序需要参考 tool's Help Page,而不是tool's dialog box,这点很重要:Do not follow the tool's dialog box to get the order of parameters; follow the tool's Help page (browse to Interpreting a tool reference page link at the end). Parameters are arranged on a tool dialog box by "display order" not by the actual order.

Executing a system tool

The following code example shows the execution of the Buffer tool from the Analysis toolbox. The required parameters for the tool are defined. In this case, strings are used to define the input, output, and buffer distance properties, so the call to the tool is easier to read.

[C#]

using System;
using System.Threading;
// Add references to esriSystem for licensing and IVariantArray.
using ESRI.ArcGIS.esriSystem;
// Add a reference to the geoprocessing namespace.
using ESRI.ArcGIS.Geoprocessing; // Call this method from your main.
private static void RunBuffer()
{
// Create the geoprocessor.
IGeoProcessor2 gp = new GeoProcessorClass(); //注意左边接口的写法,更要注意右边类的名称后缀带个Class!!
                                                  //这个地方和Geoprocessor不一样!!
gp.OverwriteOutput = true;
IGeoProcessorResult result = new GeoProcessorResultClass();
// Create a variant array to hold the parameter values.
IVariantArray parameters = new VarArrayClass();
object sev = null;
try
{
// Populate the variant array with parameter values.
parameters.Add(@"C:\data\california.gdb\cities");
parameters.Add(@"C:\data\california.gdb\cities_buff");
parameters.Add("1000 Meters");
// Execute the tool."Buffer_analysis" 这个字符串可以在ArcGIS帮助下面的功能项介绍中语法说明中找到,就是那个函数名称!!!!
result = gp.Execute("Buffer_analysis", parameters, null);
// Wait until the execution completes.
while (result.Status == esriJobStatus.esriJobExecuting)
Thread.Sleep(1000);
// Wait for 1 second.
// Print geoprocessring messages.
Console.WriteLine(gp.GetMessages(ref sev));
}
catch (Exception ex)
{
// Print a generic exception message.
Console.WriteLine(ex.Message);
// Print geoprocessing execution error messages.
Console.WriteLine(gp.GetMessages(ref sev));
}
}

Executing a custom tool

In addition to using the existing tools and toolboxes provided by Esri, you can also execute custom tools, such as model tools and script tools, that exist in custom toolboxes. The process is the same for system or custom tools when you use IGeoProcessor2.Execute. As all system toolboxes are readily available to the geoprocessor, you do not need to add the toolbox to the geoprocessor. However, you must add the custom toolbox to the geoprocessor using the AddToolbox method.
The following code example shows how to execute the CalculateBestPath custom tool in the BestPath.tbx toolbox:
The only difference between running a system tool and a custom tool is adding the custom toolbox to the geoprocessor. For more information on system and custom tools, see Essential geoprocessing vocabulary in the ArcGIS Desktop Help system.

[C#]

public void SampleCalculateBestPathToolGping()
{
// Initialize the geoprocessor.
IGeoProcessor2 gp = new GeoProcessorClass();
// Add the BestPath toolbox.
gp.AddToolbox(@"C:\SanDiego\BestPath.tbx");
// Generate the array of parameters.
IVariantArray parameters = new VarArrayClass();
parameters.Add(@"C:\SanDiego\source.shp");
parameters.Add(@"C:\SanDiego\destination.shp");
parameters.Add(@"C:\SanDiego\bestpath.shp");
object sev = null;
try
{
// Execute the model tool by name.
gp.Execute("CalculateBestPath", parameters, null);
Console.WriteLine(gp.GetMessages(ref sev));
}
catch (Exception ex)
{
// Print geoprocessing execution error messages.
Console.WriteLine(gp.GetMessages(ref sev));
}
}
Always surround your code with try-catch blocks, because the Execute method throws an exception if the tool fails to run.

Using the geoprocessor managed assembly(是一个托管程序集)

The following are the general steps to run a tool:
  1. Add a reference toESRI.ArcGIS.Geoprocessor.(如果你需要使用工具的执行结果,你也可以引用ESRI.ArcGIS .Geoprocessing:You may also need to add the ESRI.ArcGIS.Geoprocessing assembly if you want to use, for example, the result object or list datasets.)
  2. Additionally, add areference to the toolbox assembly to which the tool belongs. If you use more than one tool from different toolboxes, also add managed assemblies for those toolboxes.
  3. Create thegeoprocessor object(注意是通过Geoprocessor类,就是我们平常所说的用某个类实例化一个对象。注意:p是小写).
  4. Add the path to the custom toolbox if you are running a custom tool.
  5. Create a tool process object and set the parameter values(参数值直接对具体工具设置).
  6. Call the Execute method on the geoprocessor.

Executing a system tool with managed assembly(我发现我平常用的比较多的就是这种情况:Geoprocessor)

In the following code example, the Buffer tool is executed with the same parameter values by using the managed assemblies:

[C#]

// Add the geoprocessor namespace.
using ESRI.ArcGIS.Geoprocessor;
// Add the toolbox assembly.需要哪个就得引用这个工具所在的程序集
using ESRI.ArcGIS.AnalysisTools; public void SampleBufferTool()
{
// Create the geoprocessor.
Geoprocessor GP = new Geoprocessor();
// Create the tool process object.
ESRI.ArcGIS.AnalysisTools.Buffer bufferTool = new
ESRI.ArcGIS.AnalysisTools.Buffer();
// Set parameter values.
bufferTool.in_features = @"D:\St_Johns\data.mdb\roads";
bufferTool.out_feature_class = @"D:\St_Johns\data.mdb\roads_Buffer";
bufferTool.buffer_distance_or_field = "distance";
object sev = null;
try
{
// Execute the tool.
GP.Execute(bufferTool, null);
Console.WriteLine(GP.GetMessages(ref sev));
}
catch (Exception ex)
{
// Print geoprocessing execution error messages.
Console.WriteLine(GP.GetMessages(ref sev));
}
}

Executing a custom tool with managed assembly

Custom toolboxes do not have any managed assembly. Therefore, the simplest way to run a custom tool is by using IVariantArray and executing the tool by name. The Execute method of the geoprocessor is overloaded and has an additional argument list that allows you to execute a tool by specifying the tool name, the parameters of the tool, and the ITrackCancel interface. First, add your custom toolbox to the geoprocessor using the AddToolbox method. See the following code example:

[C#]

public void SampleCalculateBestPathTool()
{
// Initialize the geoprocessor.
Geoprocessor GP = new Geoprocessor();
// Add the BestPath toolbox.
GP.AddToolbox(@"C:\SanDiego\BestPath.tbx");
// Generate the array of parameters.
IVariantArray parameters = new VarArrayClass();
parameters.Add(@"C:\SanDiego\source.shp");
parameters.Add(@"C:\SanDiego\destination.shp");
parameters.Add(@"C:\SanDiego\bestpath.shp");
object sev = null;
try
{
// Execute the model tool by name.
GP.Execute("CalculateBestPath", parameters, null);
Console.WriteLine(GP.GetMessages(ref sev));
}
catch (Exception ex)
{
// Print geoprocessing execution error messages.
Console.WriteLine(GP.GetMessages(ref sev));
}
}
The process of executing a custom tool is same whether you use the geoprocessing assembly or the geoprocessor managed assembly. The only difference is in creating the geoprocessor.
You can generate a toolbox assembly for a custom toolboxusing the integrated development environment (IDE) framework in Visual Studio .NET. To do so, use the ArcGIS Toolbox Reference dialog box. For more information, see ArcGIS Toolbox Reference dialog box(推荐使用这种方法对你自定义的工具项进行程序集包装!!). Once an assembly is created, you can use it in the same way as a system toolbox assembly.To run a tool in the background geoprocessing, use the ExecuteAsync method instead. For more information, see Running a geoprocessing tool using background geoprocessing.

IGPProcess Interface(只是一个接口而已,从单词Process来看IGPProcess是一个动词性的接口)

private static void RunTool(Geoprocessor geoprocessor,IGPProcess process, ITrackCancel TC)
 {         //Geoprocessor 是名词,是主语;IGPProcess是动词接口,是谓语!!!!
            // Set the overwrite output option to true
            geoprocessor.OverwriteOutput = true;
            // Execute the tool            
            try
            {
                geoprocessor.Execute(process, null);
                ReturnMessages(geoprocessor);
            }
            catch (Exception err)
            {
                Console.WriteLine(err.Message);
                ReturnMessages(geoprocessor);
            }
 }

地理处理的环境设置

在Arcmap下面的操作Toolbox里面的工具的时候,有时候会设置一些环境变量,在AE里面会怎么做呢?

(1)如果知道自己操作的相关接口,可以使用IRasterAnalysisEnvironment,如下代码:

ILocalOp pLocalOp = new RasterLocalOpClass();

IWorkspaceFactory pEnvWf = new RasterWorkspaceFactoryClass();

IWorkspace pEnvRws = pEnvWf.OpenFromFile(strTempDir, 0);

IRasterAnalysisEnvironment pRasAnaEnv = (IRasterAnalysisEnvironment)pLocalOp;
       pRasAnaEnv.OutWorkspace = pEnvRws;

(2)如果是通过GP操作,则

public static bool RasterZonalStatistics(IFeatureClass pFc,string strZoneField,
            IRaster pRasterValue,  string outRaster,string strStatisticType = "MINIMUM",string ignoreNoData = "DATA")
        {
            try
            {
                Geoprocessor pGeoprocessor = new Geoprocessor();
                ISpatialReference spatialReference = null;
                IGeoDataset pGeoDataset = pFc as IGeoDataset;
                if (pGeoDataset != null) spatialReference = pGeoDataset.SpatialReference;
                ZonalStatistics pZonalStatistics = new ZonalStatistics
                {
                    in_zone_data = pFc,
                    zone_field = strZoneField,
                    in_value_raster = pRasterValue,
                    out_raster = outRaster,
                    statistics_type = strStatisticType,
                    ignore_nodata = ignoreNoData
                };

pGeoprocessor.OverwriteOutput = true;
                //pGeoprocessor.SetEnvironmentValue("workspace", strTempDir);
                if (spatialReference != null)
                    pGeoprocessor.SetEnvironmentValue("outputCoordinateSystem", spatialReference.FactoryCode);
                object ob = pGeoprocessor.Execute(pZonalStatistics, null);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

现在的问题是:SetEnvironmentValue里面的参数怎么设置,我在AO的帮助里面找不到详细的帮助,但是在google里面搜索,找到arcgis的官网帮助连接如下:

http://resources.arcgis.com/en/help/arcobjects-net/conceptualhelp/#/Using_environment_settings/0001000001n5000000/,有Using
environment settings栏目,最下方有参数名称,可以自由设置。

 
 
 

GP中Geoprocessor.Execute(string name, IVariantArray parameters, ITrackCancel trackCancel)的更多相关文章

  1. Java中如何将String转成Date

    Java中如何将String转成Date 最近在开发Json数据反序列化为Java对象的时候发现spring mvc 和 Jackson 对Date类型对支持不是特别好,虽然在Java对象序列化为Js ...

  2. struts2 action配置时 method 省略不写 默认执行方法是父类ActionSuppot中的execute()方法

    struts2 action配置时 method 省略不写 默认执行方法是父类ActionSuppot中的execute()方法

  3. java中特殊的String类型

    Java中String是一个特殊的包装类数据有两种创建形式: String s = "abc"; String s = new String("abc"); 第 ...

  4. C# 中怎么将string转换成int型

    int intA = 0;1.intA =int.Parse(str);2.int.TryParse(str, out intA);3.intA = Convert.ToInt32(str);以上都可 ...

  5. c#中 uint--byte[]--char[]--string相互转换汇总

    原文:c#中 uint--byte[]--char[]--string相互转换汇总 在在做一些互操作的时候往往需要一些类型的相互转换,比如用c#访问win32api的时候往往需要向api中传入DWOR ...

  6. C++中int与string的转化

    C++中int与string的转化 int本身也要用一串字符表示,前后没有双引号,告诉编译器把它当作一个数解释.缺省情况下,是当成10进制(dec)来解释,如果想用8进制,16进制,怎么办?加上前缀, ...

  7. java和js中int和String相互转换常用方法整理

    java中int和String的相互转换常用的几种方法: int  > String int i=10;String s="";第一种方法:s=i+""; ...

  8. jmeter从CSV中获取非正常string

    jmeter从CSV中获取非正常string,如CSV中有一列值为{"firstname":"Jade"},那么在beanshell中如何获取并解析? 一般的用 ...

  9. 关于cxf生成客户端代码中的JAXBElement<String>

    1.使用自动生成的java文件中的 ObjectFactory构造入参 关于cxf生成客户端代码中的JAXBElement<String>    在使用cxf或者x-fire进行webse ...

随机推荐

  1. top和nvidia-smi无法显示占用GPU的PID问题

    通过nvidia-smi查看显卡使用情况,发现显卡在被占用,但是却没有提示占用显卡的进程id, 这时可以输入 fuser -v /dev/nvidia* 可以查看到, 再利用sudo kill -9 ...

  2. 开始PYTHON之路

    曾经的功献给了球场酒精 曾经的激情也献给了爱情 曾经的智商用来副本求生 曾经的VB6老迈的只剩点0 曾经的SQL2000都不兼容 曾经........ 还有一些理想没有实现 还得继续在这个世界谋生 岁 ...

  3. leetcode题解 9. Palindrome Number

    9. Palindrome Number 题目: Determine whether an integer is a palindrome. Do this without extra space. ...

  4. linux 路由表 的一些相关资料

    linux 路由表维护 查看 Linux 内核路由表 使用下面的 route 命令可以查看 Linux 内核路由表. # route Destination Gateway Genmask Flags ...

  5. PowerDesigner生成PowerBuilder扩展属性~

      PowerDesigner版本:11.0.0.1363 步骤: 一.打开PowerDesigner新建模型->物理数据模型(Physical Data Model). 二.在常规选项 DBM ...

  6. VIM快速复制多行

    在vim中快速复制粘贴多行   用vim写代码时,经常遇到这样的场景,复制多行,然后粘贴. 这样做:1. 将光标移动到要复制的文本开始的地方,按v进入可视模式.2. 将光标移动到要复制的文本的结束的地 ...

  7. 【linux基础】linux不能进入系统

    博主遇到的这个问题其实主要原因是系统内核和NVIDIA的GPU版本不匹配. 主要是系统内核自动更新,而GPU驱动没有对应的更新造成的. 又要涉及NVIDIA驱动的安装,这个安装真的很鸡肋... 需要注 ...

  8. 动态改变Spring定时任务执行频率

    @Component@EnableSchedulingpublic class updateCronTask implements SchedulingConfigurer { public stat ...

  9. 高吞吐低延迟Java应用的垃圾回收优化

    高吞吐低延迟Java应用的垃圾回收优化 高性能应用构成了现代网络的支柱.LinkedIn有许多内部高吞吐量服务来满足每秒数千次的用户请求.要优化用户体验,低延迟地响应这些请求非常重要. 比如说,用户经 ...

  10. 爬虫基础之urllib库(代码演示)

    # 自定义opener   from urllib.request import ProxyHandler,build_opener from urllib.error import URLError ...