C
C#yorimirus

❔ Synchronise an object across two threads?

Hello. I have an object that I use to wait listen for a message from a TcpConnection. However, while it is waiting, the connection could get lost. So I have a field for that called _connectionLost and I have an event that sets this field to false. The problem is that this event is fired from a different thread than the one that does the actual waiting. So when this field is changed, the other thread doesn't recognize that the value changed, so it will continue waiting for a message, even though it's pointless. When I look at it using a debugger, it still says _connectionLost is false. I have verified that the event gets properly fired and the field actually gets set. It's just that the other thread doesn't see that this change happened. What can I do to make sure the other thread sees the change? I tried locks, tokens and the volatile keyword. None seem to do anything.
Y
yorimirus386d ago
Here is the code:
Y
yorimirus386d ago
The weird thing is, the OnMessageReceived event is also run on a different thread than the one that actually waits, but this time, all the properties get properly set. The TCPConnection is abstracted away to an interface because I have a specific way I communicate through this connection. The WaitForResponse methods are the ones where the thread continuously checks for a message. While the events get fired on a different thread, that manages the actual connection. Anything else I can do? I'm out of ideas. Thanks in advance.
S
Sossenbinder386d ago
One thing which comes to my mind right away would be to use a TaskCompletionSource to await on, which you can fulfill in your event handler. That might make the whole looping logic a lot easier and you can probably even get away with fields altogether, keeping all state in the context of your method. Besides that, how does the event logic look like? Usually the event handlers run on the raising thread, unless specified otherwise I guess what you might need to investigate is whether you have multiple threads entering WaitForResponse, which could potentially reset your _gotResponse field even after it has been signalled as ready due to concurrent execution
Y
yorimirus386d ago
yeah I throw an exception when that happens that's what the _waitingForResponse field is for TaskCompletionSource? Never heard of that. Will take a look at it. Thanks
A
Anton386d ago
while (!_gotResponse && (DateTime.Now - startTime).TotalSeconds < timeout)
Thread.Sleep(10);
while (!_gotResponse && (DateTime.Now - startTime).TotalSeconds < timeout)
Thread.Sleep(10);
yeah, never do this TaskCompletionSource is a classic for this scenario And also do use CancellationToken
Y
yorimirus386d ago
What does a TaskCompletionSource do? I'm not quite sure what it does from the microsoft documentation.
A
Anton386d ago
it lets you treat events as tasks, that is, await until some event happens, without blocking the thread or sleeping
Y
yorimirus386d ago
Ohh. So in the ConnectionLost event, I just set the TaskCompletionSource as completed?
S
Sossenbinder386d ago
It's a perfect match for event backed waiters Yeah
Y
yorimirus386d ago
Never heard of this class, but sounds like the exact thing I need here
S
Sossenbinder386d ago
You should maybe also read up on synchronization primitives like Mutex or Semaphore, your if check is not entirely safe, multiple threads can still get through
Y
yorimirus386d ago
Yeah I have used SemaphoreSlim a few times before. Might be a good idea to completely rewrite this class tbh.
A
Anton386d ago
also use TimeSpan for the timeouts
Y
yorimirus386d ago
I wonder why the MessageReceived event works fine though -_- Okay I will go try it out, thanks a lot
A
Anton386d ago
Race conditions only show themselves once in 1000, it works until it doesn't
Y
yorimirus386d ago
Actually it seems like I won't need any timespans now. If the events themselves set the task as complete, then I just need to use Task.WhenAny(task, Task.Delay(timeout * 1000)) to make it automatically abort.
A
Anton386d ago
I mean don't pass in the timeout as an int
Y
yorimirus386d ago
oh
A
Anton386d ago
you have TimeSpan for this it's a value type too
Y
yorimirus386d ago
yeah that's a good idea, no idea how I missed that Alright, managed to implement it the correct way. That still didn't work but after some further investigation, it wasn't because of multithreading but some completely different code entirely. Despite that, thanks a lot for your help. I managed to learn something new today thanks to you.
A
Anton386d ago
you're welcome
A
Accord385d ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server
More Posts
❔ Ok to reference both a nuget package, and the project source it's built from while I make changes?I'm wondering about the best practice handling a project that I am deploying privately as a nuget pa❔ VS SQL Server Object Explorer Default Click BehaviorIs there an option for changing the on click behavior of items in the SQL Server Object Explorer lik❔ Regex helpI have this regex: ```(?<![\[\]])(?:"&QUOTE&"([^"]*?)"&QUOTE&"|[^",\[\]]+)(?![\[\]])``` And when p❔ E2E Test - Start MVC projectHi, im using a testing tool for E2E testing and wondered how to get a MVC project started so the t❔ implementing licensing system in my appHi guys, I would like to implement some kind of license system to my app written in c#. I've been coI want to connect an esp32 to VS (WPF) C# via BLE, can anyone help? Maybe a tutorial or an example?I want to read some sensors with the ESP32 Dev, this works very well and i can display the data in m✅ ResolvePackageAssets is failing because it can't find the NuGet fallback folderI installed something called Godot portably on a USB which ended up being more invasive than everybo❔ How to calculate event expression?like ```c# var result = a+b-c+d-c+d-b+a; ``` ``a,b,c,d`` are all events, and each of them contains m❔ Class Diagram Design questionSo I am doing this design puzzle in Heads First Design Pattern book. So for those who don´t know th✅ telling a console app to exithow do i tell a console app to stop and close the window?❔ I need help for my GameCan everyone help me with my game for my school project, I need help with the scripting? My Code doe❔ Microsoft.XmlSerializer.Generator causes failure to load assembly System.RuntimeHey all, as a way to get my program running under NativeAOT I've been looking into the Microsoft.Xml✅ Make method implemented in interface accessible from implementing typei have an interface ```csharp interface ICL { public IEnumerable<ICLPlatform> GetPlatforms() { ❔ ASP.NET, MongoDB, C#does anyone have experience with c#, mongodb and ASP.NET? I have a project and I need to get data to✅ Is there a working code editor for blazor server?i found one for blazor wasm https://github.com/serdarciplak/BlazorMonaco but that one does not work ✅ Multiple inheritance questionI have a partial class webform that is inheriting a base page class. Inside it there are multiple re❔ How to automatically set version of project to know what version deployed on specific server?The problem is that there is bunch of clients with different versions of .net core and netfx projecthow to make a target that will disappear after shooting a couple of times this is my scripts i havebut it doesnt seem to want to destroy https://paste.mod.gg/mppnwkqnmukq/2❔ ✅ Choosing an appropriate data structureSo I have a list of objects and I want one in the list to be active and the rest to be inactive. I ❔ Saving User DataI have it set up through properties, but I'm having a lot of trouble with showing it on other forms