Threading, concept problem, C#

Markus Freitag 3,791 Reputation points
2023-05-25T18:20:55.23+00:00

Hello!

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.

Problems:

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());

Thread()
{
	DoIt();
	EvRequestProgram.Set();
   // 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

C#
C#
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.
11,108 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 68,236 Reputation points
    2023-05-25T22:26:35.54+00:00

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

    https://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentdictionary-2?view=net-7.0

    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(() =>
    {
       DoIt();
    
       // technically lock not needed because only 1 thread running.
       lock(MyOwnData)
       {
          MyOwnData.Add(3, new OwnData());
       }
    });
    
    if (!thread.Wait(10000))
    {
        thread.Abort();
    	throw new Exception(TIMEOUT__PROGRAM);
    }
      
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.