Threading, concept problem, C#

Markus Freitag 3,181 Reputation points


I am looking for an example where I can handle 2 processes at the same time.

Idea is await, the feature of C#

I have an editing object that can be updated from both sides.


TestSecondTask(m_cancelTokenSource.Token, testPanel);

I have to, I can't call the function with async.

How can I solve this?

If have a normal class

Another idea would be via a normal thread and then via an event to enable the switch?

How do the experts see this? What would be a good safe and simple solution?

Like this way?

protected AutoResetEvent EvRequestProgram;
EvRequestProgram = new AutoResetEvent(false);

SortedDictionary<int, OwnData> MyOwnData = new SortedDictionary<int, OwnData>();
MyOwnData.Add(index, new OwnData());

   // I think no Reset needed.
   MyOwnData.Add(3, new OwnData());
// Can I add items from the main thread and from the working thread?
// From MainThread  
if (!EvRequestProgram.WaitOne(10000))
	throw new Exception(TIMEOUT__PROGRAM);

Perhaps someone can give a quick example of how I can populate the dictionary or delete items at the same time.

Thanks for tips and your help!

Is it better to restart the thread or is there some kind of break /silence mode? How would we restart it?

enter image description here

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
8,240 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce ( 36,581 Reputation points

    for two concurrent threads to update the same Dictionary you need to use locks, or the concurrent dictionary:

    also in your example, the main thread blocks until the background thread completes, so there is no advantage to background thread except to implement the timeout. but you fail to kill the background thread on the timeout, so not clear the use case.

    simpler code:

    var MyOwnData = new SortedDictionary<int, OwnData>
       {index, new OwnData()}
    var thread = Thread.Run(() =>
       // technically lock not needed because only 1 thread running.
          MyOwnData.Add(3, new OwnData());
    if (!thread.Wait(10000))
    	throw new Exception(TIMEOUT__PROGRAM);

0 additional answers

Sort by: Most helpful