gpt4 book ai didi

c# - 高枕无忧确保异步方法已完成

转载 作者:行者123 更新时间:2023-11-30 20:06:37 25 4
gpt4 key购买 nike

目前正在使用 cloud/azure 和 windows phone 7 进行项目,我必须调用服务电话。

对我来说,我使用尖锐的休息很方便,但我面临着一个问题;我不知道我的上诉何时完成。

public static bool CreateUser(User userToCreate)
{
if (CheckNetwork())
{
var client = new RestClient(Global.Url);
var request = new RestRequest("/user", Method.POST);

MemoryStream ms = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(User));
ser.WriteObject(ms, userToCreate);
string json = JsonHelper.ToJson(userToCreate);

request.AddHeader("Content-type", "application/json; charset=utf-8");

request.AddParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;

try
{
object resp = null;
client.ExecuteAsync(request, response =>
{
if (response.ResponseStatus == ResponseStatus.Completed)
{
RestResponse resource = response;
string content = resource.Content;
resp = Convert.ToBoolean(JsonHelper.FromJson<string>(content));
}

});

return (bool)resp;
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
return false;
}
}
MessageBox.Show("You are not connect to the network!");
return false;
}

在这个例子中,方法在调用服务之前首先返回“resp”。我如何确定在 resp 未填充之前我不会退出此方法?

最佳答案

EventWaitHandle Wait = new AutoResetEvent(false);

client.ExecuteAsync(request, response =>
{
if (response.ResponseStatus == ResponseStatus.Completed)
{
RestResponse resource = response;
string content = resource.Content;
resp = Convert.ToBoolean(JsonHelper.FromJson<string>(content));
Wait.Set();
}
});

Wait.WaitOne();

关于c# - 高枕无忧确保异步方法已完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9598799/

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