将数据传递到 Task Continuation

Passing data into Task Continuation

我有以下方法:

private void GetHistoricalRawDataFromTextFiles(MessageHeader header, HistoricalRawDataFromTextFileSubscriptionDto dto)
{
    var computeInstance = GetComputeInstance(dto.SubscriberId, dto.ComputeInstanceId);
    var task = computeInstance.GetHistoricalRawDataFromTextFiles(dto, progress => SendProgress(header.Sender, progress));

    task.ContinueWith(myTask =>
    {
        dto.TimeSeries = myTask.Result;
        Messenger.SendTo(SubscriberId, header.Sender, MessageType.Reply, MessageTopic.HistoricalRawDataFromTextFiles, dto);
    });
}

方法computeInstance.GetHistoricalRawDataFromTextFilesreturns一个Task<List<string>>我的问题是

It is important that the header and dto instance values are captured within the lambda expression and task continuation at the time the outer method is called.

使用 lambda 表达式时,关闭的是 变量 ,而不是该变量的

只要 headerdto 不是您每次在进行方法调用之前修改的全局变量,就应该没问题。如果它们 全局变量,那么您需要找到一种方法为它们中的每一个创建一个本地副本。如果它们是引用类型,则需要克隆它们,如果它们是值类型,则需要将它们复制到 lambda 中的局部变量。

我认为您的问题可以归结为:"Is my method thread safe?"

我认为这与您在此处捕获的变量无关。

您的方法似乎无法访问shared/global源(static/global变量或字段)。(否则您需要同步)

即使这个方法被多个线程同时调用,它仍然是线程安全的,每次调用 GetHistoricalRawDataFromTextFiles 都会处理一个单独的 "realm" - 这是因为每个线程都有自己的堆叠.

因此,无论您是否使用捕获变量(指的是相同的 内存 位置)- 每次迭代您仍然会获得唯一的 dtoheader领域。

我在这里没有看到任何相同的共享内存位置问题,因为每次调用(即使是线程化的)都有自己的 space。

再次。这是假设您没有使用任何全局状态。