Windows 8 Phone のバッテリー レベルをネットワーク経由で特定の時間間隔で非同期に送信するアプリを作成しています。DispatcherTimer
特定の間隔の後にバッテリーレベルを送信するために を使用しています。
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
不正な方法で何にアクセスしようとしているのかわかりません。なぜこれが起こっているのか誰にもわかりますか?
注: プログラムのデバッグ中に興味深いことに気付きました。メソッドからメソッドSendBatteryLevel
が呼び出されると、コントロールSendAsyncRequest
から数行を実行した後SendBatteryLevel
、コントロールは に戻りSendAsyncRequest
ます。コントロールが戻った後の正確な行数を把握しようとしましたSendAsyncRequest
が、毎回異なります。そのため、SendBatteryLevel
メソッドが完全に実行される前に、この方法でメソッドが 2 回、場合によっては 3 回呼び出されます。これが原因で例外が発生している可能性があります。