工作撰寫Task writing

提供在建置流程期間執行之程式碼的工作。Tasks provide the code that runs during the build process. 工作是包含在目標中。Tasks are contained in targets. 一般工作程式庫會隨附於MSBuildMSBuild,您也可以建立自己的工作。A library of typical tasks is included with MSBuildMSBuild, and you can also create your own tasks. 如需隨附於 MSBuildMSBuild 之工作程式庫的詳細資訊,請參閱工作參考For more information about the library of tasks that are included with MSBuildMSBuild, see Task reference.

工作Tasks

工作範例包括複製一或多個檔案的 Copy、建立目錄的 MakeDir,以及編譯 Visual C#Visual C# 原始程式碼檔的 CscExamples of tasks include Copy, which copies one or more files, MakeDir, which creates a directory, and Csc, which compiles Visual C#Visual C# source code files. 每個工作都會實作為 .NET 類別,此類別會實作 ITask 介面,此介面定義於 Microsoft.Build.Framework.dll 組件中。Each task is implemented as a .NET class that implements the ITask interface, which is defined in the Microsoft.Build.Framework.dll assembly.

實作工作時有兩種方法可供使用:There are two approaches you can use when implementing a task:

  • 直接實作 ITask 介面。Implement the ITask interface directly.

  • 從協助程式類別 Task 衍生您的類別,此協助程式類別定義於 Microsoft.Build.Utilities.dll 組件中。Derive your class from the helper class, Task, which is defined in the Microsoft.Build.Utilities.dll assembly. 工作會實作 ITask 並提供部分 ITask 成員的預設實作。Task implements ITask and provides default implementations of some ITask members. 此外,記錄會更容易。Additionally, logging is easier.

這兩種情況都必須在您的類別中新增名為 Execute 的方法,這是工作執行時所呼叫的方法。In both cases, you must add to your class a method named Execute, which is the method that is called when the task runs. 這個方法不採用任何參數,並會傳回 Boolean 值:如果工作成功為 true,如果失敗為 falseThis method takes no parameters and returns a Boolean value: true if the task succeeded or false if it failed. 下例示範的工作不執行任何動作,並會傳回 trueThe following example shows a task that performs no action and returns true.

using System;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

namespace MyTasks
{
    public class SimpleTask : Task
    {
        public override bool Execute()
        {
            return true;
        }
    }
}

下列專案檔會執行此工作:The following project file runs this task:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <Target Name="MyTarget">
        <SimpleTask />
    </Target>
</Project>

如果您在工作類別上建立 .NET 屬性,則工作在執行時,也可以接收來自專案檔的輸入。When tasks run, they can also receive inputs from the project file if you create .NET properties on the task class. MSBuildMSBuild 會先立即設定這些屬性,再呼叫工作的 Execute 方法。sets these properties immediately before calling the task's Execute method. 若要建立字串屬性,請使用下列工作碼:To create a string property, use task code such as:

using System;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

namespace MyTasks
{
    public class SimpleTask : Task
    {
        public override bool Execute()
        {
            return true;
        }

        public string MyProperty { get; set; }
    }
}

下列專案檔會執行此工作,並將 MyProperty 設定成指定值:The following project file runs this task and sets MyProperty to the given value:

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
   <Target Name="MyTarget">
      <SimpleTask MyProperty="Value for MyProperty" />
   </Target>
</Project>

註冊工作Register tasks

如果專案即將執行工作,MSBuildMSBuild 必須知道如何找出包含工作類別的組件。If a project is going to run a task, MSBuildMSBuild must know how to locate the assembly that contains the task class. 工作是使用 UsingTask 元素 (MSBuild) 註冊的。Tasks are registered using the UsingTask element (MSBuild).

MSBuildMSBuild 檔案 Microsoft.Common.Tasks 是專案檔案,包含 UsingTask 元素清單,這些元素會註冊所有隨附於 MSBuildMSBuild 的工作。The MSBuildMSBuild file Microsoft.Common.Tasks is a project file that contains a list of UsingTask elements that register all the tasks that are supplied with MSBuildMSBuild. 組建每個專案時,都會自動包含此檔案。This file is automatically included when building every project. 如果在 Microsoft.Common.Tasks 中註冊的工作也在目前的專案檔中註冊,則以目前的專案檔為優先,亦即您可以使用自己的同名工作覆寫預設工作。If a task that is registered in Microsoft.Common.Tasks is also registered in the current project file, the current project file takes precedence; that is, you can override a default task with your own task that has the same name.

Tip

檢視 Microsoft.Common.Tasks 的內容即可以查看 MSBuildMSBuild 所提供之工作的清單。You can see a list of the tasks that are supplied with MSBuildMSBuild by viewing the contents of Microsoft.Common.Tasks.

從工作引發事件Raise events from a task

如果您的工作衍生自 Task 協助程式類別,您可以對 Task 類別使用下列任一 helper 方法,引發要被攔截且由任何已註冊記錄器顯示的事件:If your task derives from the Task helper class, you can use any of the following helper methods on the Task class to raise events that will be caught and displayed by any registered loggers:

public override bool Execute()
{
    Log.LogError("messageResource1", "1", "2", "3");
    Log.LogWarning("messageResource2");
    Log.LogMessage(MessageImportance.High, "messageResource3");
    ...
}

如果您的工作直接實作 ITask,您仍會引發這類事件,但必須使用 IBuildEngine 介面。If your task implements ITask directly, you can still raise such events but you must use the IBuildEngine interface. 下例示範的工作會實作 ITask 並引發自訂事件:The following example shows a task that implements ITask and raises a custom event:

public class SimpleTask : ITask
{
    public IBuildEngine BuildEngine { get; set; }

    public override bool Execute()
    {
        TaskEventArgs taskEvent =
            new TaskEventArgs(BuildEventCategory.Custom,
            BuildEventImportance.High, "Important Message",
           "SimpleTask");
        BuildEngine.LogBuildEvent(taskEvent);
        return true;
    }
}

要求設定工作參數Require task parameters to be set

您可將某些工作屬性標記為「必要」,讓所有執行工作的專案檔都必須設定這些屬性值,否則組建會失敗。You can mark certain task properties as "required" so that any project file that runs the task must set values for these properties or the build fails. 在您的工作中將 [Required] 屬性套用至 .NET 屬性,如下所示:Apply the [Required] attribute to the .NET property in your task as follows:

[Required]
public string RequiredProperty { get; set; }

RequiredAttributeMicrosoft.Build.Framework 命名空間中定義 [Required] 屬性。The [Required] attribute is defined by RequiredAttribute in the Microsoft.Build.Framework namespace.

範例Example

說明Description

以下 Visual C#Visual C# 類別會示範衍生自 Task 協助程式類別的工作。This following Visual C#Visual C# class demonstrates a task deriving from the Task helper class. 此工作會傳回 true,指出是否成功。This task returns true, indicating that it succeeded.

程式碼Code

using System;
using Microsoft.Build.Utilities;

namespace SimpleTask1
{
    public class SimpleTask1: Task
    {
        public override bool Execute()
        {
            // This is where the task would presumably do its work.
            return true;
        }
    }
}

範例Example

說明Description

以下 Visual C#Visual C# 類別會示範實作 ITask 介面的工作。This following Visual C#Visual C# class demonstrates a task implementing the ITask interface. 此工作會傳回 true,指出是否成功。This task returns true, indicating that it succeeded.

程式碼Code

using System;
using Microsoft.Build.Framework;

namespace SimpleTask2
{
    public class SimpleTask2: ITask
    {
        //When implementing the ITask interface, it is necessary to
        //implement a BuildEngine property of type
        //Microsoft.Build.Framework.IBuildEngine. This is done for
        //you if you derive from the Task class.
        public IBuildEngine BuildEngine { get; set; }

        // When implementing the ITask interface, it is necessary to
        // implement a HostObject property of type object.
        // This is done for you if you derive from the Task class.
        public object HostObject { get; set; }

        public bool Execute()
        {
            // This is where the task would presumably do its work.
            return true;
        }
    }
}

範例Example

說明Description

Visual C#Visual C# 類別會示範衍生自 Task 協助程式類別的工作。This Visual C#Visual C# class demonstrates a task that derives from the Task helper class. 它具有必要的字串屬性,會引發所有已註冊記錄器顯示的事件。It has a required string property, and raises an event that is displayed by all registered loggers.

程式碼Code

using System;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

namespace SimpleTask3
{
    public class SimpleTask3 : Task
    {
        private string myProperty;

        // The [Required] attribute indicates a required property.
        // If a project file invokes this task without passing a value
        // to this property, the build will fail immediately.
        [Required]
        public string MyProperty
        {
            get
            {
                return myProperty;
            }
            set
            {
                myProperty = value;
            }
        }

        public override bool Execute()
        {
            // Log a high-importance comment
            Log.LogMessage(MessageImportance.High,
                "The task was passed \"" + myProperty + "\".");
            return true;
        }
    }
}

範例Example

說明Description

下例示範的專案檔會叫用前一個範例的工作:SimpleTask3。The following example shows a project file invoking the previous example task, SimpleTask3.

程式碼Code

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <UsingTask TaskName="SimpleTask3.SimpleTask3"
        AssemblyFile="SimpleTask3\bin\debug\simpletask3.dll"/>

    <Target Name="MyTarget">
        <SimpleTask3 MyProperty="Hello!"/>
    </Target>
</Project>

另請參閱See also