C# Asynchronous call without EndInvoke?

前端 未结 4 1295
野趣味
野趣味 2020-12-10 05:38

Take the following classes as an example.

public class A
{
   // ...
   void Foo(S myStruct){...}
}

public class B
{
   public A test;
   // ...
   void Bar         


        
4条回答
  •  半阙折子戏
    2020-12-10 05:51

    I would say that your best option is to use the ThreadPool:

    void bar()
    {
        ThreadPool.QueueUserWorkItem(o=>
        {
            S myStruct = new S();
            test.foo(myStruct);
        });
    }
    

    This will queue the snippet for execution in a separate thread. Now you also have to be careful about something else: if you have multiple threads accessing the same instance of A and that instance modifies a variable, then you must ensure that you do proper synchronization of the variable.

    public class A
    {
        private double sum;
        private volatile bool running;
        private readonly object sync;
        public A()
        {
            sum = 0.0;
            running = true;
            sync = new object();
        }
    
        public void foo(S myStruct)
        {
            // You need to synchronize the whole block because you can get a race
            // condition (i.e. running can be set to false after you've checked
            // the flag and then you would be adding the sum when you're not 
            // supposed to be).
            lock(sync)
            {
                if(running)
                {
                    sum+=myStruct.Value;
                }
            }
        }
    
        public void stop()
        {
            // you don't need to synchronize here since the flag is volatile
            running = false;
        }
    }
    

提交回复
热议问题