我通过了#34; GetFilesRevisions_Results" GetAsync的方法,它将处理它的结果。但我想从" GetFilesRevisions_Results"返回一个整数。方法。我怎么能做到这一点? 提前谢谢!
private int GetVersionNumber(string i_sFileName)
{
#region Get latest version no.
int nVerNo = 0;
// RequestResult result;
try
{
OAuthUtility.GetAsync
(
"https://api.dropboxapi.com/1/revisions/auto/",
new HttpParameterCollection
{
{ "path", i_sFileName },
{ "access_token", accessToken },
{ "rev_limit", 1 }
},
callback: GetFilesRevisions_Results ??? How I can access return variable
);
}
catch
{
}
return nVerNo;
#endregion
}
private int GetFilesRevisions_Results(RequestResult result)
{
int nVerNo = 0;
if (result.StatusCode == 200)
{
dynamic dynJson = JsonConvert.DeserializeObject(Convert.ToString(result));
foreach (var item in dynJson)
{
nVerNo = Convert.ToInt32(item.rev);
}
}
else
{
throw new Exception("Failed to get revisions of files");
}
return nVerNo;
}
#endregion Get version Number
答案 0 :(得分:2)
您无法知道何时会调用您的回调,因此返回值不是获取int的正确方法。
您可以使用带有int参数的事件,并在GetFilesRevisions_Results
之前的return
内调用它。然后,您就可以使用来自任何此事件侦听器的整数值。
答案 1 :(得分:1)
您可能想要使用等待句柄:
AutoResetEvent waitHandle = new AutoResetEvent(false);
int nVerNoGlobalTempHolder = 0;
private int GetVersionNumber(string i_sFileName)
{
#region Get latest version no.
for (int i = 0; i < 10 && nVerNoGlobalTempHolder != 0; i++)
{
//Someone is waiting for this callback already...
//Do something like:
Thread.Sleep(500);
}
If (nVerNoGlobalTempHolder == 0) throw new Exception("timeout");
// RequestResult result;
try
{
OAuthUtility.GetAsync
(
"https://api.dropboxapi.com/1/revisions/auto/",
new HttpParameterCollection
{
{ "path", i_sFileName },
{ "access_token", accessToken },
{ "rev_limit", 1 }
},
callback: GetFilesRevisions_Results ??? How I can access return variable
);
}
catch
{
}
waitHandle.WaitOne();
int nVerNo =nVerNoGlobalTempHolder;
nVerNoGlobalTempHolder = 0;//Reset this in case you have multiple thread calling it
return nVerNo;
}
private int GetFilesRevisions_Results(RequestResult result)
{
if (result.StatusCode == 200)
{
dynamic dynJson = JsonConvert.DeserializeObject(Convert.ToString(result));
foreach (var item in dynJson)
{
nVerNoGlobalTempHolder = Convert.ToInt32(item.rev);
}
}
else
{
throw new Exception("Failed to get revisions of files");
}
WaitHandle.Set();
}
如果有多个线程调用它,它还会实现非常基本的同步。如果您不需要,请在开始时删除for循环