您正在尝试有条件地返回异步方法任务。以下是我尝试的方式。
public string DoMessage(MyObj obj)
{
string returnStatus = "Processing...";
var storageAccount = CloudStorageAccount.DevelopmentStorageAccount;
var queueClient = storageAccount.CreateCloudQueueClient();
var queue = queueClient.GetQueueReference(ConfigurationManager.AppSettings["QueueName"]);
if (queue.CreateIfNotExists()) {
}
var msg = CloudQueueMessageExtensions.Serialize(obj);
queue.AddMessage(msg);
//Task processTask = RunMessageProces();
var t = Task.Run(() => RunMessageProces());
t.Wait();
return returnStatus;
}
private async Task<string> RunMessageProces()
{
statusProcess = "Your message successfully inserted in process queue.";
await Task.Run(() => {
lock (_oQueue)
{
if (flagProcessing == true) //return when queue processing alredy started
{
return statusProcess; //Error ..??? how to return
}
flagProcessing = true; //else start processing the queue till there are messages.
}
});
statusProcess = ProcessMyMessage();
return statusProcess;
}
private string ProcessMyMessage() {...}
我缺少什么?如何在异步方法中有条件地返回字符串,这种方法也位于等待锁定匿名块(?)之内。我在任务中执行异步操作,因为由于服务的暴露部分,Do Message同时充斥着大量的调用。
答案 0 :(得分:2)
我假设您正在询问如何从任务中访问返回的值。
private async Task<string> RunMessageProces()
{
var statusProcess = "Your message successfully inserted in process queue.";
var retValue = await Task.Run(() =>
{
lock (_oQueue)
{
if (flagProcessing == true) //return when queue processing alredy started
{
return "Error"; // or some such error indicator
}
flagProcessing = true; //else start processing the queue till there are messages.
}
return string.Empty; // return a string here too....
});
// if( retValue == "Error" ) { return "Error" }
statusProcess = ProcessMyMessage();
return statusProcess;
}