James
James

Reputation: 25

Concurrency in .net for a function

I have the following code being run in multi-threading business logic:

using System;
using System.Threading.Tasks;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            var biz1 = new Biz { Some = 1, Value = "a" };
            var biz2 = new Biz { Some = 2, Value = "b" };
            var foo = new Foo();

            //thread 1
            new Task(() => foo.Run(biz1)).Start();
            //thread 2
            new Task(() => foo.Run(biz2)).Start();
            //more threads here for other Biz objects....

            Console.Read();
        }
    }

    public class Biz
    {
        public int Some { get; set; }
        public string Value { get; set; }
    }

    public class Foo
    {
        public void Run(Biz biz)
        {
            //base on the biz object do some task here

        }
    }
}

The biz object is NOT being changed at anytime during threading

Questions:

Upvotes: 1

Views: 147

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273314

  • Is foo.Run thread safe?

It sounds like your Foo.Run() is safe, it depends on what other data is accessed of course.

  • Is it better to instantiate individual Foo object to run each Biz object (the Run is the only function within Foo)?

Assuming it is safe, ie it does not use any instance data of Foo, Run() could and should be static. This would at least convey a better message to the reader.

public static class Foo
{
    public static void Run(Biz biz)
    {
        //base on the biz object do some task here

    }
}

Upvotes: 1

Related Questions