gpt4 book ai didi

c# - 异步任务如何有条件返回

转载 作者:行者123 更新时间:2023-12-02 23:49:40 24 4
gpt4 key购买 nike

您好,我正在尝试有条件地返回异步方法任务。以下是我尝试过的方法。

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() {...}

我缺少什么?如何在异步方法下有条件地返回字符串,该方法也位于等待锁匿名 block 内(?)。我在任务中执行异步操作,因为由于服务的暴露部分,Do Message 同时被大量调用淹没。

最佳答案

我假设您询问如何访问任务的返回值。

  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;
}

关于c# - 异步任务如何有条件返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37457718/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com