I am Trying to create a Windows Universal App with a Background Task.
I am trying to Write a Background task that Triggers Upon an Incoming bluetooth connection.
To prevent both the foreground and background from creating a connection. I am trying to implement the Same Mutex in Both the Foreground and Background.
When I read the Data from the Bluetooth Device I am getting the Following Error.
Object Synchronization method was called from unsynchronized block
To my Surprise this Error comes Occasionally . Am I missing Something ?
Here's My Code :
public sealed class RFBackgroundTask : IBackgroundTask
{
.... Variable declarations
public async void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
try
{
taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
Debug.WriteLine("RFComm Task Running");
hotwatchConnection = taskInstance.TriggerDetails as RfcommConnectionTriggerDetails;
socket = hotwatchConnection.Socket;
reader = new DataReader(socket.InputStream);
// n = new Notification(hotwatchConnection.RemoteDevice.HostName);
await Read();
}
catch (System.Exception e)
{
Debug.WriteLine("RFComm Task Error: {0}", e.Message);
if (ismutexReleased == false)
{
Debug.WriteLine("Releaseing mutex because of error {0}:", e.Message);
connectionMutex.ReleaseMutex();
ismutexReleased = true;
}
}
finally
{
if (ismutexReleased == false)
{
Debug.WriteLine("Releasing Mutex 2");
connectionMutex.ReleaseMutex();
}
ismutexReleased = true;
}
deferral.Complete();
}
public IAsyncAction Read()
{
return Task.Run(async () =>
{
try
{
connectionMutex = new Mutex(false, CONNECTION_MUTEX_NAME);
// Attempt to wait for the mutex
var waitResult = connectionMutex.WaitOne();
if (waitResult)
{
Debug.WriteLine("Aquired Mutex Successfully");
}
// If the wait was not successful, fail the connect operation
if (!waitResult) { throw new TimeoutException(); }
if (reader != null)
{
uint length = 500;
reader.InputStreamOptions = InputStreamOptions.Partial;
uint len = await reader.LoadAsync(length);
String message = reader.ReadString(len);
Debug.WriteLine("Read " + message + " In the First Attemnpt");
var roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings;
roamingSettings.Values["COMMAND"] = message;
//if(!message.StartsWith("01"))
//{
// await ProcessCommand(message);
//}
}
reader.Dispose();
socket.Dispose();
socket = null;
if (waitResult == true)
connectionMutex.ReleaseMutex();
ismutexReleased = true;
Debug.WriteLine("Released Mutex successfully after reading data");
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
if (ismutexReleased == false)
{
Debug.WriteLine("Releaseing mutex because of error {0}:", e.Message);
connectionMutex.ReleaseMutex();
ismutexReleased = true;
}
throw;
}
finally
{
if (ismutexReleased == false)
{
connectionMutex.ReleaseMutex();
Debug.WriteLine("Releasing Mutex");
}
ismutexReleased = true;
}
}).AsAsyncAction();
}
}
The Mutex must be released on the same thread that it was acquired.
When you await an async method you are returned to the same context, you are not guaranteed to be returned to the same thread.
Use a Semaphore instead.
Related
We have an JQuery Ajax call that will execute when a user is about to leave a page on a DNN module.
This error is being logged the whole time in the DNN logs.
How can I improve the error handling so that it doesn't log the whole time?
Here is the DNN log:
Here is the Front End Code on the Module :
$(window).on("beforeunload", function () {
ClearTempUserSessionWhenLeavePage();
});
function ClearTempUserSessionWhenLeavePage() {
if ($fromButtonEvent == false) {
var Url = $.fn.GetBaseURL() + 'DesktopModules/DNNCommon/API/Store/ClearTempUserSessionWhenLeavePage';
$.ajax({
url: Url,
type: 'GET',
async: true,
dataType: 'json',
success: function () {
},
error: function (x, y, z) {
}
}).promise().done(function () {
});
}
$fromButtonEvent = false;
}
We are inheriting the DNNApiController class on our DNNCommon class.
This is the C# method being called:
[AllowAnonymous]
[HttpGet]
public void ClearTempUserSessionWhenLeavePage()
{
if (SessionManager.GetSessionObject("NewCreatedWebUser") != null)
{
System.Web.HttpContext.Current.Session["DoNotRemoveSessionIfNotAuthenticated"] = false;
SessionManager.SetSessionObject("NewCreatedWebUser", null);
SessionManager.SetSessionObject("UserInfo", null);
SessionManager.SetSessionObject("NewCustomerCode", null);
}
}
I have attempted to add two different types of Try Catch clauses, but when I debug the code it won't hit the breakpoints and somehow it still logs the error in the DNN Admin logs. Is there perhaps a Try Catch in the DNNController class that is writing this error?
First attempt with Try Catch Clause with TaskCanceledException and TimeoutException:
[AllowAnonymous]
[HttpGet]
public void ClearTempUserSessionWhenLeavePage()
{
try
{
if (SessionManager.GetSessionObject("NewCreatedWebUser") != null)
{
System.Web.HttpContext.Current.Session["DoNotRemoveSessionIfNotAuthenticated"] = false;
SessionManager.SetSessionObject("NewCreatedWebUser", null);
SessionManager.SetSessionObject("UserInfo", null);
SessionManager.SetSessionObject("NewCustomerCode", null);
}
}
catch (Exception ex)
{
EventLogController logController = new EventLogController();
if (ex.InnerException is TimeoutException)
{
ex = ex.InnerException;
}
else if (ex is TaskCanceledException)
{
if ((ex as TaskCanceledException).CancellationToken == null || (ex as TaskCanceledException).CancellationToken.IsCancellationRequested == false)
{
ex = new TimeoutException("Timeout occurred");
logController.AddLog("Timout Occured - Clearing Temp User Session When Leave Page.", ex.ToString(), EventLogController.EventLogType.ADMIN_ALERT);
}
}
logController.AddLog("Problem Clearing Temp User Session When Leave Page.", ex.ToString(), EventLogController.EventLogType.ADMIN_ALERT);
}
}
Second attempt with a TaskCanceledException:
[AllowAnonymous]
[HttpGet]
public void ClearTempUserSessionWhenLeavePage()
{
try
{
if (SessionManager.GetSessionObject("NewCreatedWebUser") != null)
{
System.Web.HttpContext.Current.Session["DoNotRemoveSessionIfNotAuthenticated"] = false;
SessionManager.SetSessionObject("NewCreatedWebUser", null);
SessionManager.SetSessionObject("UserInfo", null);
SessionManager.SetSessionObject("NewCustomerCode", null);
}
}
catch (TaskCanceledException ex)
{
EventLogController logController = new EventLogController();
logController.AddLog("Task Cancelled Exception - Clearing Temp User Session When Leave Page.", ex.ToString(), EventLogController.EventLogType.ADMIN_ALERT);
}
}
Using Websockets, I am able to use 1 computer and 1 kinect v2.0 to generate JSON objects of the joints x,y, and z coordinates in real-time. The next steps is to have this data transferred to another computer, using possibly TCP/IP network. My question is to anyone who knows how this is done. Having this data transferred to another computer.
Output that needs to be transferred to another computer in real-time
namespace WebSockets.Server
{
class Program
{
// Store the subscribed clients.
static List<IWebSocketConnection> clients = new List<IWebSocketConnection>();
// Initialize the WebSocket server connection.
static Body[] bodies = new Body[6];
//static KinectSensor kinectSensor = null;
static CoordinateMapper _coordinateMapper;
static Mode _mode = Mode.Color;
static void Main(string[] args)
{
//const string SkeletonStreamName = "skeleton";
//SkeletonStreamMessage skeletonStreamMessage;// = new SkeletonStreamMessage { stream = SkeletonStreamName };
KinectSensor kinectSensor = KinectSensor.GetDefault();
BodyFrameReader bodyFrameReader = null;
bodyFrameReader = kinectSensor.BodyFrameSource.OpenReader();
ColorFrameReader colorFrameReader = null;
colorFrameReader = kinectSensor.ColorFrameSource.OpenReader();
_coordinateMapper = kinectSensor.CoordinateMapper;
kinectSensor.Open();
WebSocketServer server = new WebSocketServer("ws://localhost:8001");
server.Start(socket =>
{
socket.OnOpen = () =>
{
// Add the incoming connection to our list.
clients.Add(socket);
};
socket.OnClose = () =>
{
// Remove the disconnected client from the list.
clients.Remove(socket);
};
socket.OnMessage = message =>
{
if (message == "get-video")
{
int NUMBER_OF_FRAMES = new DirectoryInfo("Video").GetFiles().Length;
// Send the video as a list of consecutive images.
for (int index = 0; index < NUMBER_OF_FRAMES; index++)
{
foreach (var client in clients)
{
string path = "Video/" + index + ".jpg";
byte[] image = ImageUtil.ToByteArray(path);
client.Send(image);
}
// We send 30 frames per second, so sleep for 34 milliseconds.
System.Threading.Thread.Sleep(270);
}
}
else if (message == "get-bodies")
{
if (kinectSensor.IsOpen)
{
if (bodyFrameReader != null)
{
bodyFrameReader.FrameArrived += bodyFrameReader_FrameArrived;
}
}
}
else if (message == "get-color")
{
if (kinectSensor.IsOpen)
{
if (colorFrameReader != null)
{
colorFrameReader.FrameArrived += colorFrameReader_FrameArrived;
}
}
}
};
});
// Wait for a key press to close...
Console.ReadLine();
kinectSensor.Close();
}
private static void colorFrameReader_FrameArrived(object sender, ColorFrameArrivedEventArgs e)
{
//throw new NotImplementedException();
using (ColorFrame colorFrame = e.FrameReference.AcquireFrame()) {
if (colorFrame != null) {
var blob = colorFrame.Serialize();
foreach (var client in clients)
{
if (blob != null)
{
client.Send(blob);
Console.WriteLine("After color Blob sent");
}
}
}
}
}
private static void bodyFrameReader_FrameArrived(object sender, BodyFrameArrivedEventArgs e)
{
//throw new NotImplementedException();
bool dataReceived = false;
using (BodyFrame bodyFrame = e.FrameReference.AcquireFrame())
{
if (bodyFrame != null)
{
if (bodies == null)
{
bodies = new Body[bodyFrame.BodyCount];
}
// The first time GetAndRefreshBodyData is called, Kinect will allocate each Body in the array.
// As long as those body objects are not disposed and not set to null in the array,
// those body objects will be re-used.
bodyFrame.GetAndRefreshBodyData(bodies);
dataReceived = true;
}
}
if (dataReceived)
{
foreach (var client in clients)
{
var users = bodies.Where(s => s.IsTracked.Equals(true)).ToList();
if (users.Count>0){
string json = users.Serialize(_coordinateMapper, _mode);
Console.WriteLine("jsonstring: " + json);
Console.WriteLine("After body serialization and to send");
}
}
}
}
}
}
Try changing it from
WebSocketServer server = new WebSocketServer("ws://localhost:8001");
to
WebSocketServer server = new WebSocketServer(" ws://192.168.X.X:8001");
on the client end. Enter the IP address of the client computer and make sure both server and client are on the same network.
I'm using this code with ejabberd 15 and now is updated to 17.04 and now when I ask for MAM this just fails.
private MamQueryResult queryArchive(MamQueryIQ mamQueryIq, long extraTimeout) throws NoResponseException, XMPPErrorException, NotConnectedException {
if (extraTimeout < 0) {
throw new IllegalArgumentException("extra timeout must be zero or positive");
}
final XMPPConnection connection = connection();
MamFinExtension mamFinExtension;
PacketCollector finMessageCollector = connection.createPacketCollector(new MamMessageFinFilter(
mamQueryIq));
PacketCollector.Configuration resultCollectorConfiguration = PacketCollector.newConfiguration().setStanzaFilter(
new MamMessageResultFilter(mamQueryIq)).setCollectorToReset(
finMessageCollector);
PacketCollector resultCollector = connection.createPacketCollector(resultCollectorConfiguration);
try {
//this line works fine. send and IQ and the response is received
connection.createPacketCollectorAndSend(mamQueryIq).nextResultOrThrow();
//This line trigger an exceptions NoResponseException
Message mamFinMessage = finMessageCollector.nextResultOrThrow(connection.getPacketReplyTimeout() + extraTimeout);
mamFinExtension = MamFinExtension.from(mamFinMessage);
}
catch(Exception e) {
Log.d(Constants.TAG_DEBUG, e.getMessage(), e);
throw e;
}
finally {
resultCollector.cancel();
finMessageCollector.cancel();
}
List<Forwarded> messages = new ArrayList<>(resultCollector.getCollectedCount());
for (Message resultMessage = resultCollector.pollResult(); resultMessage != null; resultMessage = resultCollector.pollResult()) {
// XEP-313 ยง 4.2
MamResultExtension mamResultExtension = MamResultExtension.from(resultMessage);
messages.add(mamResultExtension.getForwarded());
}
return new MamQueryResult(messages, mamFinExtension, DataForm.from(mamQueryIq));
}
i found this example(https://developer.nokia.com/Community/Wiki/Windows_Phone_8_communicating_with_Arduino_using_Bluetooth) in my research to develop a bluetooth console to windows phone 8. This example work very well, except for the TERMINATE function. When i call TERMINATE function, the ReceiveMessages function still trying receive data, but there is no more socket available and it generate a system.exception. I tried a lot of workaround, but i dont have enough experience with C#, this is my first APP. Anyone know how can i workaround this situation or have a better example?
i did only 1 modificiation:
private async void AppToDevice()
{
if (!connected)
{
ConnectAppToDeviceButton.Content = "Connecting...";
PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
var pairedDevices = await PeerFinder.FindAllPeersAsync();
if (pairedDevices.Count == 0)
{
Debug.WriteLine("No paired devices were found.");
}
else
{
foreach (var pairedDevice in pairedDevices)
{
if (pairedDevice.DisplayName == DeviceName.Text)
{
connectionManager.Connect(pairedDevice.HostName);
ConnectAppToDeviceButton.Content = "Disconnect";
DeviceName.IsReadOnly = true;
//ConnectAppToDeviceButton.IsEnabled = false;
continue;
}
}
}
}
else
{
connectionManager.Terminate();
ConnectAppToDeviceButton.Content = "Connect";
}
}
I found a solution here:
WinRT: DataReader.LoadAsync Exception with StreamSocket TCP
I did only a few modifications:
public void Terminate()
{
try
{
if (socket != null)
{
taskLoadLength.Cancel();
taskLoadLength.Close();
taskLoadMessage.Cancel();
taskLoadMessage.Close();
socket.Dispose();
dataReadWorker.CancelAsync();
dataReader.Dispose();
dataWriter.Dispose();
isInicialized = false;
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
private void ReceiveMessages(object sender, DoWorkEventArgs ev)
{
while (true)
{
try
{
// Read first byte (length of the subsequent message, 255 or less).
//uint sizeFieldCount = await dataReader.LoadAsync(1);
taskLoadLength = dataReader.LoadAsync(1);
taskLoadLength.AsTask().Wait();
uint sizeFieldCount = taskLoadLength.GetResults();
if (sizeFieldCount != 1)
{
// The underlying socket was closed before we were able to read the whole data.
return;
}
// Read the message.
uint messageLength = dataReader.ReadByte();
taskLoadMessage = dataReader.LoadAsync(messageLength);
taskLoadMessage.AsTask().Wait();
uint actualMessageLength = taskLoadMessage.GetResults();
//uint actualMessageLength = await dataReader.LoadAsync(messageLength);
if (messageLength != actualMessageLength)
{
// The underlying socket was closed before we were able to read the whole data.
return;
}
// Read the message and process it.
string message = dataReader.ReadString(actualMessageLength);
MessageReceived(message);
}
catch (AggregateException ae)
{
MessageBox.Show(ae.Message);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}
I am using DDE client to attach and listen stock market prices. That client has a callback method I implemented what to do when it receives price changes. The problem is that I get StackOverflowException (periodically and not at the same time interval). I found something about Thread.BeginCriticalRegion(), but I'm not sure if it would help. I have a few more hours until market opening when I can test it.
I would be more than greatful if someone could give me an idea how to override this exception.
Thanks in advance,
Aleksandar
IList<SymbolObject> _symbols; //initialized when the app runs for the first time
void _ddeClient_Advise(object sender, DdeAdviseEventArgs args)
{
if (!IsReady)
return;
if (string.IsNullOrEmpty(args.Text))
{
_logMessages.LogMessagesAdd("advise dde symbol", string.Format("args.Text is empty or NULL for {0}", args.Item), true);
return;
}
try
{
string[] argsArray = args.Text.Replace("\0", "").Replace('\0'.ToString(), "").Split(' '); // sometimes happens here
var list = _symbols.Where(s => s.DDESymbol == args.Item).ToList();
if (list.Count == 0)
return;
decimal? val = null;
try
{
var stringParts = StringUtils.CleanProphitXUrl(argsArray[0]).Split('.');
argsArray = null;
if (stringParts.Length >= 2)
val = decimal.Parse(stringParts[0] + "." + (stringParts[1].Length > 2 ? stringParts[1].Substring(0, 2) : stringParts[1]));
else
val = decimal.Parse(stringParts[0]);
stringParts = null;
}
catch (Exception ex)
{
_logMessages.LogMessagesAdd("call Price Alerts application service", ex.Message, true);
return;
}
foreach (var l in list)
{
if (_lastPrices[l.DDESymbol] == null)
continue;
if (_lastPrices[l.DDESymbol].ToString() != val.ToString())
{
try
{
_quotePublishingService.PublishQuote(l.DDESymbolId, l.Symbol, args.Item, val, WebSyncPublisherUrl,
PublishingChannel); // a call to wcf service
}
catch (Exception ex)
{
_logMessages.LogMessagesAdd("call the service", ex.Message, true); // save to sql db
return;
}
_lastPrices[l.DDESymbol] = val.ToString();
}
}
list = null;
val = null;
}
catch
{
}
}
public static string CleanProphitXUrl(string value) // StringUtils.CleanProphitXUrl snippet
{
StringBuilder sb = new StringBuilder();
sb.Append(value.Substring(0, value.LastIndexOf(".") + 1));
try
{
value = value.Replace('\r'.ToString(), "").Replace('\t'.ToString(), "").Replace('\n'.ToString(), "");
for (int i = sb.Length; i < value.Length; i++)
{
if (char.IsNumber(value[i]))
sb.Append(value[i]);
}
}
catch
{
}
return sb.ToString();
}
A StackOverflowException is caused by making to many method calls usually resulting from unintended recursion. Based on a cursory check of the code you posted I do not believe it is the culprit. The problem likely lies somewhere else.