使用TaskCompletionSource的异步方法中的死锁

时间:2018-09-12 08:02:06

标签: c# asp.net .net asp.net-web-api taskcompletionsource

我正在尝试公开一个ASP.NET Web API,该API必须捕获并返回照片作为附件。 我正在使用CameraControl.Devices 2.1.0-beta来控制尼康DSLR和.NET 4.6。

但是我的行为很不一致。有时第一个HTTP请求设法返回一张照片,但是从那里开始,在组成最终的HttpResponseMessage之前,它就停止了,然后HTTP请求挂起并超时。我相信这是异步操作造成的僵局。它始终执行DeviceManager_PhotoCaptured中的逻辑,该逻辑将照片从DSLR传输到文件夹。有时候,它甚至可以从单个请求中拍摄两张照片。

我在做什么错?您知道更好的方法吗?

using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using CameraControl.Devices;
using CameraControl.Devices.Classes;

public class PhotosController : ApiController
{
    public string FolderForPhotos = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "Test");

    private TaskCompletionSource<string> TaskCompletionSource = null;
    private CameraDeviceManager DeviceManager = null;

    // GET api/photos
    public async Task<HttpResponseMessage> Get()
    {
        TaskCompletionSource = new TaskCompletionSource<string>();

        DeviceManager = new CameraDeviceManager();
        DeviceManager.StartInNewThread = false;
        DeviceManager.PhotoCaptured += DeviceManager_PhotoCaptured;

        DeviceManager.ConnectToCamera();
        DeviceManager.SelectedCameraDevice.CapturePhoto();

        var fileName = await TaskCompletionSource.Task.ConfigureAwait(continueOnCapturedContext: false);

        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        var stream = new FileStream(fileName, FileMode.Open);
        result.Content = new StreamContent(stream);
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        result.Content.Headers.ContentDisposition.FileName = Path.GetFileName(fileName);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
        result.Content.Headers.ContentLength = stream.Length;
        return result;
    }

    private void DeviceManager_PhotoCaptured(object sender, PhotoCapturedEventArgs eventArgs)
    {
        if (eventArgs == null)
        {
            TaskCompletionSource.TrySetException(new Exception("eventArgs is empty"));
            return;
        }
        try
        {
            string fileName = Path.Combine(FolderForPhotos, Path.GetFileName(eventArgs.FileName));
            // if file exist try to generate a new filename to prevent file lost. 
            // This useful when camera is set to record in ram the the all file names are same.
            if (File.Exists(fileName))
                fileName =
                    StaticHelper.GetUniqueFilename(
                    Path.GetDirectoryName(fileName) + "\\" + Path.GetFileNameWithoutExtension(fileName) + "_", 0,
                    Path.GetExtension(fileName));

            // check the folder of filename, if not found create it
            if (!Directory.Exists(Path.GetDirectoryName(fileName)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(fileName));
            }
            eventArgs.CameraDevice.TransferFile(eventArgs.Handle, fileName);
            // the IsBusy may used internally, if file transfer is done should set to false  
            eventArgs.CameraDevice.IsBusy = false;

            TaskCompletionSource.TrySetResult(fileName);
        }
        catch (Exception exception)
        {
            TaskCompletionSource.TrySetException(exception);
            eventArgs.CameraDevice.IsBusy = false;
        }
        finally
        {
            DeviceManager.CloseAll();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我知道了:

我必须将TaskCompletionSource设为静态字段。我猜出于某种原因,当它是一个实例字段时,它最终被释放或分离。 private static TaskCompletionSource<string> TaskCompletionSource = null;