C# 参数化方法的后台工作程序
如何在C#中为以下方法添加后台工作程序C# 参数化方法的后台工作程序,c#,C#,如何在C#中为以下方法添加后台工作程序 背景工人的工作如下,我希望这将是有益的。如果适合您的需要,请尝试: BackgroundWorker worker = new BackgroundWorker(); worker.WorkerReportsProgress = true; worker.DoWork += new DoWorkEventHandler(worker_DoWork); worker.RunWorkerAsync(); 工人的工作如下: private void worke
背景工人的工作如下,我希望这将是有益的。如果适合您的需要,请尝试:
BackgroundWorker worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerAsync();
工人的工作如下:
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
//Write your logic here. For example call your method
}
您可以将此方法用作后台工作程序的事件处理程序,但仍必须使用worker.RunWorkerAsyn()调用它
将它称为普通方法将运行在同一个线程
中,您可能需要考虑详细阐述您的问题。不太清楚 也就是说,假设您想问的是如何运行filemove(string,string)
方法作为BackgroundWorker.DoWork
事件的入口点,那么您有两个选项
我的首选是提供一个匿名方法作为实际的事件处理程序,并利用变量捕获来提供实际的参数。例如:
void StartBackgroundWorker(string file, string destinationPath)
{
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (sender, e) => filemove(file, destinationPath);
bw.RunWorkerAsync();
}
void StartBackgroundWorker(string file, string destinationPath)
{
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (sender, e) =>
{
Tuple<string, string> args = (Tuple<string, string>)e.Argument;
filemove(args.Item1, args.Item2);
};
bw.RunWorkerAsync(Tuple.Create(file, destinationPath));
}
通过这种方式,BackgroundWorker
获得一个与所需签名匹配的事件处理程序,并且您仍然可以在不更改其签名的情况下调用您的方法
如果出于某种原因需要访问方法中的BackgroundWorker
对象,则必须更改方法的签名,以便传递引用。但您仍然可以将其与上述方法混合使用:
void StartBackgroundWorker(string file, string destinationPath)
{
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (sender, e) => filemove(file, destinationPath, bw);
bw.RunWorkerAsync();
}
如果您想完全避免捕获变量(但为什么?),仍然可以这样做。但是在这种情况下,您需要将所需的值传递给RunWorkerAsync()
方法。例如:
void StartBackgroundWorker(string file, string destinationPath)
{
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (sender, e) => filemove(file, destinationPath);
bw.RunWorkerAsync();
}
void StartBackgroundWorker(string file, string destinationPath)
{
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (sender, e) =>
{
Tuple<string, string> args = (Tuple<string, string>)e.Argument;
filemove(args.Item1, args.Item2);
};
bw.RunWorkerAsync(Tuple.Create(file, destinationPath));
}
void StartBackgroundWorker(字符串文件,字符串目标路径)
{
BackgroundWorker bw=新的BackgroundWorker();
bw.DoWork+=(发送方,e)=>
{
Tuple args=(Tuple)e.参数;
文件移动(args.Item1、args.Item2);
};
RunWorkerAsync(Tuple.Create(file,destinationPath));
}
当然,如果需要,您可以使用上面的
元组
传递BackgroundWorker
对象引用。我已经编辑了您的标题。请参阅“”,其中的共识是“不,他们不应该”。