我正在使用BackgroundUploadAsync
API将文件上传到OneDrive。大多数情况下该函数工作正常,但有时调用会返回此错误消息:
系统正忙于之前的后台上传...
我尝试关闭并重新启动应用程序,但我仍然遇到同样的错误。
知道为什么会这样吗?如何重新初始化与OneDrive的连接?
以下是执行上传的代码:
public static async Task<string> BackgroundUploadFile<T>(
string skydriveFolderId,
T objectToSerialize,
string fileNameInSkyDrive,
BackgroundTransferPreferences backgroundTransferPreferences =
BackgroundTransferPreferences.AllowCellularAndBattery)
{
string fileId = string.Empty;
try
{
var storageFolder = await GetSharedTransfersFolder();
StorageFile isolatedstorageFile = await storageFolder.CreateFileAsync(
fileNameInSkyDrive,
CreationCollisionOption.ReplaceExisting);
using (var writer = new StreamWriter
(await isolatedstorageFile.OpenStreamForWriteAsync()))
{
// convert to string
var _String = Serialize(objectToSerialize);
await writer.WriteAsync(_String);
}
Client.BackgroundTransferPreferences = backgroundTransferPreferences;
LiveOperationResult liveOpResult = await Client.BackgroundUploadAsync(
skydriveFolderId,
new Uri("/shared/transfers/" + fileNameInSkyDrive, UriKind.Relative),
OverwriteOption.Overwrite);
fileId = (string)liveOpResult.Result["id"];
Debug.WriteLine("BackgroundUploadFile: " + fileNameInSkyDrive);
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Upload Error", MessageBoxButton.OK);
Debug.WriteLine("\nError - BackgroundUploadFile: " + e.Message);
}
return fileId;
}
另外,我有一个怀疑&#34; OneDrive正在锁定帐户,因为有后台任务被卡住了#34;并且OneDrive不会释放/释放它们?!
答案 0 :(得分:1)
您是否有可能在其他任何地方致电BackgroundUploadAsync
?尝试使用SemaphoreSlim
保护它,您可能正在使用它
// class member
SemaphoreSlim _semaphore = new SemaphoreSlim(1);
public static async Task<string> BackgroundUploadFile<T>(..)
{
// ...
LiveOperationResult liveOpResult;
await _semaphore.WaitAsync();
try
{
liveOpResult = await Client.BackgroundUploadAsync(
skydriveFolderId,
new Uri("/shared/transfers/" + fileNameInSkyDrive, UriKind.Relative),
OverwriteOption.Overwrite);
}
finally
{
_semaphore.Release();
}
// ...
}
答案 1 :(得分:0)
我无法使BackgroundUploadFile按预期工作,而是使用附加的上传功能解决它:
public static async Task<string> UploadFile<T>( string skydriveFolderId,
T objectToSerialize,
string fileNameInSkyDrive )
{
string fileID = string.Empty;
using ( var memoryStream = new MemoryStream() )
{
try
{
var serializer = new DataContractJsonSerializer( objectToSerialize.GetType() );
serializer.WriteObject( memoryStream, objectToSerialize );
memoryStream.Seek( 0, SeekOrigin.Begin );
LiveOperationResult liveOpResult = await Client.UploadAsync( skydriveFolderId, fileNameInSkyDrive, memoryStream, OverwriteOption.Overwrite );
fileID = (string)liveOpResult.Result [ "id" ];
Debug.WriteLine( "\nUploadFile: " + fileNameInSkyDrive );
}
catch ( Exception e )
{
MessageBox.Show( e.Message, "Upload Error", MessageBoxButton.OK );
Debug.WriteLine( "\nError - UploadFile: " + e.Message );
}
}
return fileID;
}
THX