0

我正在使用新的 HttpClient 类将一些数据上传到服务器,所以我不得不使用新的操作符,比如 await/async。我有以下问题:如何阻止调用者线程等到第一个文件被上传,然后移动到下一个文件。

    public async Task Upload(string filename)
    {
        HttpRequestMessage message = new HttpRequestMessage();

        StreamContent streamContent = new StreamContent(new FileStream(filename, FileMode.Open));
        message.Method = HttpMethod.Put;
        message.Content = streamContent;
        message.RequestUri = new Uri(webURI);

        HttpResponseMessage response = await httpClient.SendAsync(message);

        //I want to reach this point untill I will start to upload next file
        if (response.IsSuccessStatusCode)
        {
            //do something
        }


    }

    void uploadFiles()
    {
        foreach (string filename in filenames)
        {
            Upload(filename);
        }
    }

感谢您对我的问题的任何关注。

4

1 回答 1

1

await在您上传下一个文件之前上传已完成:

async void uploadFiles()
{
    foreach (string filename in filenames)
    {
        await Upload(filename);
    }
}
于 2012-11-22T12:30:33.613 回答