Consider use case: I need to pass a parameter to QueueUserWorkItem
:
ThreadPool.QueueUserWorkItem((o) =>
{
var item = o as MyObject;
},
item);
Then requirements changed and I now need to pass 2 objects. So I would have to write something like:
ThreadPool.QueueUserWorkItem((o) =>
{
var items = o as Tuple<MyObject,MyObject2>;
},
new Tuple<MyObject,MyObject2>(item1, item2));
Is there a cleaner way to achieve this in C# 9 ?
CodePudding user response:
You can use this overload if your target framework has it. Then you can do:
ThreadPool.QueueUserWorkItem(args => {
var first = args.Item1; // it's of type string already
var second = args.Item2; // this is int
}, ("a", 1), false);
Or:
ThreadPool.QueueUserWorkItem(args => {
var first = args.first; // it's of type string already
var second = args.second; // this is int
}, (first: "a", second: 1), false); // name parameters here instead of using Item1 Item2
And in single parameter case you don't need to cast type from object (this overload accepts generic Action<T>
delegate).
CodePudding user response:
You can always leverage closures in C# lambdas and ingore passing parameter completely:
var item1 = ...;
var item2 = ...;
ThreadPool.QueueUserWorkItem(_ =>
{
Console.WriteLine(item1);
Console.WriteLine(item2);
});
Also personally I would consider switching to Task.Run
instead of ThreadPool.QueueUserWorkItem
(though there should be some considiration due to some differences in behaviour).