I'm trying to expose an ASP.NET Web API which has to capture and return a photo as an attachment. I'm using CameraControl.Devices 2.1.0-beta to control my Nikon DSLR and .NET 4.6.
But I'm getting a very inconsistent behavior. Sometimes the first HTTP request manages to return a photo but from there on it stops right before composing the final HttpResponseMessage and then the HTTP request just hangs and timeouts. I believe it's a deadlock caused by the async operations. It always executes the logic in DeviceManager_PhotoCaptured which transfers the photo from the DSLR to a folder. Sometimes somehow it even takes two photos from a single request.
What am I doing wrong? Do you know a better way to do this?
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();
}
}
}
I figured it out:
I had to make the TaskCompletionSource
a static field. I guess, for some reason, when it was an instance field it ended up deallocated or detached.
private static TaskCompletionSource<string> TaskCompletionSource = null;