Reputation: 7914
I need to develop following scenario. I have System.Threating.Timer. On each timer tick, some values are retrieved from hardware device, this way:
lock (_synch)
{
//Read some values
}
Also I have many methods invoked in background thread, they also wants to read/write on COM to talk with device, for example:
bool WriteSometghing ()
{
lock(_synch)
{
//Write to device
}
}
It works fine. All of this is synchronised as should, there are no simultaneous access to device from threads. However, I need to my WriteSomething method to be called asynchronously to prevent blocking other operations in my background thread. So WriteSomething should start third thread, do all needed operations and destroy third thread. Of course, still I need to be sure, that there are no simultaneous access to hardware. So it should be synchronised with method called on timer tick. Also I need to synchronise WriteSomething calls (every call is fired on UDP packet receive), so WriteSomething can be invoked simultaneously but all operations inside should be syncrhonised between WriteSomething calls.
Method WriteSomething has to be called from background thread and also third thread should be created from my background thread, in place of current WriteSomething call. Can I simply create third thread as I described, put WriteSomething there and leave my lock as is? Will it be synchronised as should between my 3 threads (first - timer tick, second - background thread, third - background thread for WriteSomething).
Can you give me some tips, how it should be done?
Upvotes: 0
Views: 360
Reputation: 133995
You can simply create a Task to call WriteSomething
.
var task = Task.Factory.CreateNew(WriteSomething);
That will spin up a new thread to execute the WriteSomething
method. The lock
inside the WriteSomething
method will provide the necessary synchronization. If you want to harvest the return value, simply access task.Result
.
Do note that accessing task.Result
requires that the task complete. So if you write:
var task = Task.Factory.CreateNew(WriteSomething);
var rslt = task.Result;
The thread will block until the task is finished. Of course, you can do any arbitrary processing between when you start the task and when you harvest the result.
If you can't use Task
, there are other ways to do this. For example:
bool result;
Thread t = new Thread((s) => { result = WriteSomething(); });
// at some point you'll want to harvest the result:
t.Join();
// Now you can access result
Upvotes: 2