如何从异步Task返回一些值

时间:2014-01-16 06:55:31

标签: c# task-parallel-library

我正在使用多部分数据表单上传文件,我需要保留上传文件的文件描述。我正在使用以下代码

FileDescription temp = new FileDescription();
var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<IEnumerable<FileDescription>>(t =>
{

    if (t.IsFaulted || t.IsCanceled)
    {
        throw new HttpResponseException(HttpStatusCode.InternalServerError);
    }

    var fileInfo = streamProvider.FileData.Select(i =>
    {
        var info = new FileInfo(i.LocalFileName);
        temp.AssociatedSchool = 1;
        temp.FileName = info.Name;
        temp.LocalFileName = i.LocalFileName;
        temp.FileSize = info.Length / 1024;
        temp.IsFileValid = true;
        temp.NoOfRecords = 1;
        temp.UploadedBy = 1;
        return temp;
    });
    return fileInfo;
});

此代码不会将值设置为temp对象。谁能告诉我另一种获取价值的方法? task.Result始终为null。如何从线程中获取值?

1 个答案:

答案 0 :(得分:1)

尝试像这样更改您的样本

var descriptions = Request.Content.ReadAsMultipartAsync(streamProvider)
                          .ContinueWith<IEnumerable<FileDescription>>(t =>
            {
                if (t.IsFaulted || t.IsCanceled)
                {
                    throw new HttpResponseException(HttpStatusCode.InternalServerError);
                }

                var fileInfo = streamProvider.FileData.Select(i =>
                {
                    var info = new FileInfo(i.LocalFileName);
                    return new FileDescription(){
                        AssociatedSchool = 1;
                        FileName = info.Name;
                        LocalFileName = i.LocalFileName;
                        FileSize = info.Length / 1024;
                        IsFileValid = true;
                        NoOfRecords = 1;
                        UploadedBy = 1;
                    }
                });
                return fileInfo;
            }).Result;

var temp = descriptions.First();//Possibly you need FirstOrDefault