Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在委托声明中使用包装功能的方法_C#_Multithreading - Fatal编程技术网

C# 在委托声明中使用包装功能的方法

C# 在委托声明中使用包装功能的方法,c#,multithreading,C#,Multithreading,我真的不喜欢创建委托来提供线程功能。如果我目前正在使用方法A来做工作,但后来意识到在线程中运行会更好,那么现在我必须创建一个委托和另一个方法来实际运行线程。所以现在我有了方法A的起始线程,然后通过委托给方法B来工作 我的问题是: *我可以在线程声明本身中包装功能吗* 差不多 System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart( new de

我真的不喜欢创建委托来提供线程功能。如果我目前正在使用方法A来做工作,但后来意识到在线程中运行会更好,那么现在我必须创建一个委托和另一个方法来实际运行线程。所以现在我有了方法A的起始线程,然后通过委托给方法B来工作

我的问题是: *我可以在线程声明本身中包装功能吗*

差不多

System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(
                new delegate()
                {
            SqlConnection Connection = Helpers.ConnectionHelper.CreateConnection();
            SqlCommand cmd = new SqlCommand("MarkNotificationRead", Connection);
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.Add("@id", SqlDbType.BigInt).Value = this.id;

            Connection.Open();

            try
            {
                cmd.ExecuteNonQuery();
            }

            catch 
            {

            }

            Connection.Close();
                });

我以前在某个地方见过类似的例子,但现在再也找不到了。

你的例子非常接近,只是一些小的语法变化-去掉新的
,和
()

另一种方法是使用lambda语法,在该语法中,您可以摆脱
ThreadStart
调用:

System.Threading.Thread t = new System.Threading.Thread(
            () =>
            {
                  ...
            });

:谢谢。非常简单的解决方案!
System.Threading.Thread t = new System.Threading.Thread(
            () =>
            {
                  ...
            });