C# 多线程编程:解决命名空间冲突问题
这些代码无法运行,因为名称为'Thread'的命名空间与C#中的System.Threading.Thread类冲突。需要将命名空间更改为其他名称,例如'ThreadDemo'。同时,需要在Form1类的开头添加以下代码来引用System.Threading命名空间:
using ThreadDemo = System.Threading;
以下是修改后的代码示例:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ThreadDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ThreadDemo.Thread thread1 = new ThreadDemo.Thread(new ThreadDemo.ThreadStart(DoWork));
ThreadDemo.Thread thread2 = new ThreadDemo.Thread(new ThreadDemo.ThreadStart(DoWork));
ThreadDemo.Thread thread3 = new ThreadDemo.Thread(new ThreadDemo.ThreadStart(DoWork));
thread1.Start();
thread2.Start();
thread3.Start();
thread1.Join();
thread2.Join();
thread3.Join();
MessageBox.Show("All threads completed.");
}
private void DoWork()
{
for (int i = 1; i <= 60; i++)
{
// Simulate some work
ThreadDemo.Thread.Sleep(1000);
}
}
}
}
通过以上修改,您就可以成功运行代码,实现多线程编程的功能。
原文地址: https://www.cveoy.top/t/topic/mFgn 著作权归作者所有。请勿转载和采集!