【发布时间】:2011-06-12 03:47:31
【问题描述】:
我有一个运行良好的 Winforms 应用程序。在处理设备的串行数据期间,使用 BackgroundWorkerThread 来管理 GUI 可用性。
一切正常。
现在,我正在添加一个新方法,并复制我在其他形式中所做的。但是我遇到了跨线程异常。
我这样声明我的 BWT:
BackgroundWorker bw = new BackgroundWorker();
bw.WorkerSupportsCancellation = true;
bw.DoWork += DownloadGpsDataFromDevice;
bw.WorkerReportsProgress = true;
bw.RunWorkerAsync();
然后我有一个像这样声明的方法,它在后台工作:
private void DownloadGpsDataFromDevice(object sender, DoWorkEventArgs e)
{
_performScreenUpdate = true;
tsStatus.Text = "Downloading GPS Data...";
Invalidate();
Refresh();
Common.WriteLog("Extracting raw GPS data. Sending LL.");
ReplyString raw = DeviceServices.ExecuteCommand("$LL");
DeviceServices.ExecuteCommand("$LL");是完成工作的位,但我在上一行遇到异常,我在其中登录到文本文件。现在,这让您担心 - 写入文件。但是,我在另一个 BWT 中已经这样做了数千次。
我使写作线程安全。这是我的 Common.WriteLog 方法:
public static void WriteLog(string input)
{
lock (_lockObject)
{
WriteLogThreadSafe(input);
}
}
private static void WriteLogThreadSafe(string input)
{
Directory.CreateDirectory(LogFilePath);
StreamWriter w = File.AppendText(LogFilePath + @"\" + LogFileName);
try
{
w.WriteLine(string.Format("{0}\t{1}", DateTime.Now, input));
}
catch (Exception e)
{
System.Console.WriteLine("Error writing to log file!");
System.Console.WriteLine("Tried to write: [" + input + "]");
System.Console.WriteLine("Failed with error: [" + e.Message + "]");
}
finally
{
w.Close();
}
}
这已经工作了很长时间。我不相信错误存在。我想我可能只是在通话中遗漏了什么?
【问题讨论】:
标签: c# multithreading backgroundworker