我正在製作一個應用程序,在特定的時間間隔後通過網絡異步發送Windows 8 Phone的電池電量。我正在使用DispatcherTimer
呼叫在特定時間間隔後發送電池電量。在什麼情況下你會得到`System.UnauthorizedAccessException`?
DispatcherTimer timer = new DispatcherTimer(); //Create the timer instance
timer.Interval = TimeSpan.FromSeconds(15); //Set the timer interval
timer.Tick += SendAsyncRequest; //Call this procedure after the time ends
timer.Start();
我想使用POST請求發送電池電量。
void SendAsyncRequest(object sender, object e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://192.168.2.17/android_connect/add_device.php");
request.Method = "POST";
request.BeginGetRequestStream(new AsyncCallback(SendBatteryLevel), request);
}
現在,我在那裏用於發送的實際請求(SendBatteryLevel
)碼的代碼的心臟是如下:
void SendBatteryLevel(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
using (Stream postStream = request.EndGetRequestStream(asynchronousResult))
{
string username = "CoolSops";
string deviceId = "WindowsPhone";
string batteryLevel = Windows.Phone.Devices.Power.Battery.GetDefault().RemainingChargePercent.ToString();
string post_param = "username=" + username + "&device_id=" + deviceId + "&battery_level=" + batteryLevel;
try
{
byte[] requestBody = System.Text.Encoding.UTF8.GetBytes(post_param);
postStream.Write(requestBody, 0, requestBody.Length);
SendingStatus.Text = "Battery data sent";
postStream.Close();
}
catch (Exception e)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
ErrorStatus.Text = e.ToString();
});
Console.WriteLine(e.Message + "\n\n" + e.Source + "\n\n" + e.StackTrace);
}
}
}
其中SendingStatus
和ErrorStatus
是TextBlock
秒。當我執行此代碼時,我得到一個System.UnauthorizedAccessException
。是異常的詳細信息如下:
A first chance exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll
An exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll and wasn't handled before a managed/native boundary
我不明白我試圖訪問未經授權的方式。任何人都可以告訴爲什麼發生這種情況?
注意: 我在調試程序時注意到了一個有趣的事情。當從方法SendAsyncRequest
調用方法SendBatteryLevel
時,在從SendBatteryLevel
執行幾行後,控制返回到SendAsyncRequest
。我試圖找出確切的線數,之後控制回到SendAsyncRequest
,但每次都會變化。因此,方法SendBatteryLevel
在方法完全執行之前以這種方式調用兩次或有時三次。可能是這是什麼導致發生異常。
我錯過了什麼,或者你忘了描述_unable來做這件事嗎? – 2013-03-07 04:51:00
我無法將電池電量發送到我的網絡應用程序。 – TheRookierLearner 2013-03-07 04:54:18
是的,你的問題是這樣說的。但是......您能否詳細說明您遇到的特定問題,使您可以發送電池電量_? – 2013-03-07 04:58:29